我有一个包含一些十六进制数字的文本文件,我正在尝试将其转换为十进制。我可以成功转换它,但似乎在循环存在之前它读取了一些不需要的字符,所以我收到以下错误。
Traceback (most recent call last):
File "convert.py", line 7, in <module>
print >>g, int(x.rstrip(),16)
ValueError: invalid literal for int() with base 16: ''
我的代码如下
f=open('test.txt','r')
g=open('test1.txt','w')
#for line in enumerate(f):
while True:
x=f.readline()
if x is None: break
print >>g, int(x.rstrip(),16)
每个十六进制数换行输入
回溯表明文件末尾可能有一个空行。
你可以这样修复它:
f = open('test.txt','r')
g = open('test1.txt','w')
while True:
x = f.readline()
x = x.rstrip()
if not x: break
print >> g, int(x, 16)
另一方面,最好使用for x in f
代替readline
。不要忘记关闭您的文件或更好地使用with
为您关闭它们:
with open('test.txt','r') as f:
with open('test1.txt','w') as g:
for x in f:
x = x.rstrip()
if not x: continue
print >> g, int(x, 16)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)