如何在python中迭代文件

use*_*879 38 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: ''
Run Code Online (Sandbox Code Playgroud)

我的代码如下

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)
Run Code Online (Sandbox Code Playgroud)

每个十六进制数字都以新行输入

joa*_*uin 66

回溯表明可能在文件末尾有一个空行.你可以像这样解决它:

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)
Run Code Online (Sandbox Code Playgroud)

另一方面,最好使用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)
Run Code Online (Sandbox Code Playgroud)

  • 在最近的版本中,后者的缩进沉重度可以降低:`open('test.txt','r')为f,open('test1.txt','w')为g` (19认同)
  • @delnan,好新的东西!当压痕不是问题时,我仍然更喜欢双线形式.我读的更好...... (4认同)
  • 这是Python习语的"清晰度"的一个很好的例子 - 不需要EOF,readline(),writeline()或任何胆量 - 只是概念:迭代一个文件中的行,转换并导出到另一个文件.非常好!(1) (4认同)

小智 12

只需使用for x in f: ...,这可以提供一行一行,更短和可读(部分原因是它在文件结束时自动停止)并且还节省了rstrip调用,因为已经规定了尾随换行符.

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

  • 这不会删除尾随的换行:`python -c'with open("file.txt")as f:print(repr([l [-1] for l in f]))'`返回``的许多实例在Python 2.7.12和3.4.5上的n` (3认同)

Hug*_*ell 7

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(str(int(line, 16)))
                outf.write('\n')
            except ValueError:
                print("Could not parse '{0}'".format(line))
Run Code Online (Sandbox Code Playgroud)