我需要逐行读取文件。还需要确保正确处理编码。
我写了以下代码:
#!/bin/bash
import codecs
filename = "something.x10"
f = open(filename, 'r')
fEncoded = codecs.getreader("ISO-8859-15")(f)
totalLength = 0
for line in fEncoded:
totalLength+=len(line)
print("Total Length is "+totalLength)
此代码不适用于所有文件,在某些文件上我得到一个
Traceback (most recent call last):
File "test.py", line 11, in <module>
for line in fEncoded:
File "/usr/lib/python3.2/codecs.py", line 623, in __next__
line = self.readline()
File "/usr/lib/python3.2/codecs.py", line 536, in readline
data = self.read(readsize, firstline=True)
File "/usr/lib/python3.2/codecs.py", line 480, in read
data = self.bytebuffer + newdata
TypeError: can't concat bytes to str
我使用的是 python 3.3,脚本必须适用于这个 python 版本。
我做错了什么,我无法找出哪些文件有效,哪些无效,甚至一些普通的 ASCII 文件也失败了。