我在尝试打开目录中的所有.txt文件时出现错误,当我的目录中只有1个txt文件时,我的代码可以正常工作,否则会弹出以下消息:
Traceback (most recent call last):
File "/Users/Name/Desktop/TCSS 142/Project 2/project2.py", line 17, in <module>
for line in file:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 3: ordinal not in range(128)这是我的代码:
import glob
# Returns a list of all filenames ending in .txt
# precondition: none
# postcondition: a list of all filenames in the current directory
# with a .txt extension
def getFilesInDir():
filenames = glob.glob('./*.txt')
for i in range(len(filenames)):
filenames[i] = filenames[i][2:]
return filenames
files = getFilesInDir()
for el in files:
file = open(el, 'r')
for line in file:
print(line)
file.close()发布于 2016-06-03 15:27:26
好的,所以@Evert的评论解决了我的问题,当我打开文件时,我的打开语句看起来是这样的:
file = open(el, 'r', encoding = 'cp1252')发布于 2016-06-07 17:18:28
您的默认编码(用于读取文件)显示为ASCII;它不能读取的字符显示为(Windows)智能引号("curly“撇号')。
为了能够读取文件,您需要指定其编码。我不认为0x92是一个有效的UTF代码点(但我可能弄错了);因为它是Windows的智能引用,所以可以试试Windows latin alphabet encoding cp1252
file = open(el, 'r', encoding = 'cp1252')https://stackoverflow.com/questions/37608085
复制相似问题