无法在OS X上让Python读取我的.txt文件
我想让IDLE读取我的.txt文件,但不知道为什么就是不行。我在学校的时候用Windows电脑和记事本做的同样的事情,效果很好,但现在在我的Mac上用IDLE却找不到这个.txt文件。
我确保文件和IDLE在同一个文件夹里,而且文件是纯文本格式的,但还是出现了错误。以下是我使用的代码:
def loadwords(filename):
f = open(filename, "r")
print(f.read())
f.close()
return
filename = input("enter the filename: ")
loadwords(filename)
这是我输入文件名“test.txt”并按下回车后收到的错误信息:
Traceback (most recent call last):
File "/Computer Sci/My programs/HW4.py", line 8, in <module>
loadwords(filename)
File "/Computer Sci/My programs/HW4.py", line 4, in loadwords
print(f.read())
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
4 个回答
0
file = open(textfile, "r", encoding = "utf8")
read = file.read()
file.close()
print(read)
这行代码的意思是把一个叫做“textfile.txt”的文本文件的名字存储在一个变量里,变量的名字也叫“textfile”。这样我们就可以在后面的代码中用“textfile”来代表这个文件了。
1
你需要用合适的编码打开文件。此外,你还应该从这个方法中返回一些东西,否则你就无法对文件进行任何操作。
试试这个版本:
def loadwords(filename):
with open(filename, 'r', encoding='utf8') as f:
lines = [line for line in f if line.strip()]
return lines
filename = input('Enter the filename: ')
file_lines = loadwords(filename)
for eachline in file_lines:
print('The line is {}'.format(eachline))
这一行 [line for line in f if line.strip()]
是一种叫做列表推导式的写法。它是下面这种写法的简化版:
for line in f:
if line.strip(): # check for blank lines
lines.append(line)
3
你看到的这个错误是因为你的Python解释器试图把文件当作ASCII字符来加载,但你要读取的文本文件并不是ASCII编码。它很可能是UTF-8编码的(在最近的OSX系统中,UTF-8是默认编码)。
在open
命令中添加编码信息应该会更有效:
f = open(filename, "r" "utf8")
另一种解决方法是回到TextEdit,打开你的文件,然后选择复制(或者使用另存为 shift-cmd-S),这样你可以重新保存文件,这次选择ASCII编码。不过,如果编码选项列表中没有ASCII,你可能需要手动添加它。
这个其他问题和被接受的答案提供了一些关于如何选择你要读取的文件编码的更多想法。