我正在嘗試在Python 3的目錄中執行一些基本的文件解析。此代碼在Python 2.7中完美工作,但我無法弄清楚Python 3.2中出現了什麼問題。解析目錄內的問題Python 2.7與3.2
進口SYS,操作系統,重新
filelist = os.listdir('/Users/sbrown/Desktop/Test')
os.chdir('/Users/sbrown/Desktop/Test')
for file in filelist:
infile = open(file, mode='r')
filestring = infile.read()
infile.close()
pattern = re.compile('exit')
filestring = pattern.sub('so long', filestring)
outfile = open(file, mode='w')
outfile.write(filestring)
outfile.close
exit
這是後仰的錯誤:
Traceback (most recent call last):
File "/Users/bunsen/Desktop/parser.py", line 9, in <module>
filestring = infile.read()
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 3131: ordinal not in range(128)`
我解析的文件都是文本文件。我試圖在utf-8的方法參數中指定編碼,但那不起作用。有任何想法嗎?提前致謝!
如果我指定的編碼爲UTF-8,這裏是拋出的錯誤:
Traceback (most recent call last):
File "/Users/sbrown/Desktop/parser.py", line 9, in <module>
filestring = infile.read()
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 3131: ordinal not in range(128)`
感謝您的幫助Evpok。默認編碼是US-ASCII。當我強制utf-8編碼到我的問題時,我還添加了錯誤信息。詛咒你Python 3! – drbunsen 2011-05-19 23:25:16
哇,同樣的痕跡,有多奇怪!打印(infile.encoding)返回哪個編碼? – Evpok 2011-05-20 06:43:15
感謝您的幫助!我把它與Lennart的幫助一起工作。 – drbunsen 2011-05-20 10:05:36