2011-04-20 63 views
27

我有一个带有一些十六进制数字的文本文件,我试图将它转换为十进制。我可以成功转换它,但似乎在循环存在之前它读取一些不需要的字符,所以我得到以下错误。如何迭代python中的文件

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) 

每个十六进制数来在输入新行

+0

嘛,拿调试,并找出问题的“X”值引起的问题。也许你有一个BOM文件? – 2011-04-20 16:20:15

+0

@RestRisiko:如果有BOM,错误信息会显示。不,它只是试图将空字符串''''提供给'int'。 – delnan 2011-04-20 16:21:11

回答

49

回溯表明您可能在文件末尾有空行。 你能解决这个问题是这样的:

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) 
+12

后者的缩进量可以在更新的版本中减少:'open('test.txt','r')为f,open('test1。 txt','w')as g' – delnan 2011-04-20 16:32:58

+4

@delnan,很好的新东西!当缩进不是问题时,我更喜欢双线形式。我读得更好... – joaquin 2011-04-20 16:38:19

+1

哎呀!为什么downvote?特别是当OP已经接受答案时,downvotes没有解释就没有用处。 – joaquin 2011-04-20 16:42:15

12

只要使用for x in f: ...,这给你行线后,更短且可读性(部分原因是它在文件结束时自动停止),并且还为您节省rstrip调用,因为已经规定了尾随的换行符。

该错误是由退出条件造成的,该条件永远不会成立:即使文件耗尽,readline将返回一个空字符串,而不是None。另外请注意,您仍然可能遇到空行问题,例如在文件的末尾。添加if line.strip() == "": continue会使代码忽略空行,无论如何,这可能是件好事。

+0

这不会去掉尾随的换行符:'python -c'with open(“file.txt”)as f:print(repr([l [-1] for l in f])'''返回' \ n在Python 2.7.12和3.4.5上 – JamesTheAwesomeDude 2017-05-02 04:02:55

1

这可能是因为在你输入文件的末尾空行。

试试这个:

for x in f: 
    try: 
     print int(x.strip(),16) 
    except ValueError: 
     print "Invalid input:", x 
1

你应该了解EAFP VS LBYL

from sys import stdin, stdout 
def main(infile=stdin, outfile=stdout): 
    if isinstance(infile, basestring): 
     infile=open(infile,'r') 
    if isinstance(outfile, basestring): 
     outfile=open(outfile,'w') 
    for lineno, line in enumerate(infile, 1): 
     line = line.strip() 
     try: 
      print >>outfile, int(line,16) 
     except ValueError: 
      return "Bad value at line %i: %r" % (lineno, line) 

if __name__ == "__main__": 
    from sys import argv, exit 
    exit(main(*argv[1:])) 
+0

我会使用lineno + 1 – 2011-04-20 18:17:30

5
with open('test.txt', 'r') as inf, open('test1.txt', 'w') as outf: 
    for line in inf: 
     line = line.strip() 
     if line: 
      try: 
       outf.write(int(line, 16)) 
       outf.write('\n') 
      except ValueError: 
       print("Could not parse '{0}'".format(line)) 
+0

Hugh - outf.write(int(line,16))为你工作吗?我的代码与您的代码完全相同,只是我正在尝试编写字典d。我收到一个ValueError。如下所示:Traceback(最近一次调用最后一次): 文件“./test.py”,第22行,在 outf.write(d) ValueError:关闭文件的I/O操作 – blehman 2013-08-18 06:22:15