用python读取txt文件,文件的内容包含一列数如下:
F:\RenYongguo\cats\3\3.jpg
F:\RenYongguo\cats\3\4.jpg
F:\RenYongguo\cats\3\5.jpg
…
但是运行时报错,读取的文件路径为
IOError: [Errno 22] invalid mode (‘wb’) or filename:‘F:\RenYongguo\cats\xef\xbb\xbf3\3.jpg’
,上网看了一些资料,原来在python的file对象的readline以及readlines程序中,针对一些UTF-8编码的文件,开头会加入BOM来表明编码方式。
解决方法有很多种:
1.这篇博客引用codecs模块,来判断前三个字节是否为BOM_UTF8。如果是,则剔除\xef\xbb\xbf字节。
2.另外还有很多解决方案,可以判断列表中是否有\xef\xbb\xbf字符,如果有,用replace()替换为空的,代码如下:
f = open("2017-5-17-1.txt","r")
lightSen = []
for line in f.readlines():
if '\xef\xbb\xbf' in line:
str1 = line.replace('\xef\xbb\xbf','')#用replace替换掉'\xef\xbb\xbf'
lightSen.append(int(str1.strip()))#strip()去掉\n
else:
lightSen.append(int(line.strip()))
print(lightSen)
f.close