使用Python从文件中读取

时间:2015-01-11 01:37:32

标签: python file encoding

很长一段时间以来,我一直在尝试制作一个问答游戏,它将从文本文件中读取问题和答案并将其显示在屏幕上。我使用了以下功能:

def start_quiz() :
    text_file = open("quiz_python.txt", "r", encoding = "utf-8")
    for lines in text_file :
        print(lines)

我通过标准记事本文字处理器制作.txt文件,并使用“Utf-8”编码保存文件(在同一目录中)。但是,当我启动程序时,它在一开始就崩溃了。更令人惊讶的是,当我在IDLE中使用F5运行该程序时,它运行得非常好!那一刻我不知道该怎么想,因为这很奇怪。有什么建议吗?

谢谢, 胜利者。

1 个答案:

答案 0 :(得分:-1)

你没有说哪个版本的python。我使用2.x

我认为是因为你正在使用编码行。

Python 2.7.8 (default, Dec  6 2014, 13:17:43) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def start_quiz() :
...     text_file = open("quiz_python.txt", "r", encoding = "utf-8")
...     for lines in text_file :
...         print(lines)
... 
>>> start_quiz()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in start_quiz
TypeError: 'encoding' is an invalid keyword argument for this function
>>> def start_quiz() :
...     text_file = open("quiz_python.txt", "r")
...     for lines in text_file :
...         print(lines)
... 
>>> start_quiz()
stuff in a file
>>> 

我在处理文件时个人使用with open

>>> with open('workfile', 'r') as f:
...     read_data = f.read()

如果你需要编码;将所有或每一行读取到变量str并在其上运行str.encode(encoding='UTF-8',errors='strict')