我需要将我拥有的文件中的字符串转换为整数。有问题的字符串只是一个数字。
L= linecache.getline('data.txt', 1)
L=int(L)
print L
我收到错误:
ValueError: invalid literal for int() with base 10: '\xef\xbb\xbf3\n'
如何将此字符串转换为整数?
The file contains an UTF-8 BOM.
>>> import codecs
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
linecache.getline
does not support encoding.
Use codecs.open
:
with codecs.open('data.txt', encoding='utf-8-sig') as f:
L = next(f)
L = int(L)
print L
您的文件以BOM开头。在尝试解析数字之前将其剥离。