如何在python中迭代文件

时间:2020-12-07 14:29:20

I have a text file with some hexadecimal numbers and i am trying to convert it to decimal. I could successfully convert it, but it seems before the loop exist it reads some unwanted character and so i am getting the following error.

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

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: ''

My code is as follows

我的代码如下

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)

Each hexadecimal number comes in a new line for input

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

5 个解决方案

#1


57  

The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this:

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

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)

On the other hand it would be better to use for x in f instead of readline. Do not forget to close your files or better to use with that close them for you:

另一方面,最好在f中使用x而不是readline。不要忘记关闭您的文件或更好地使用它们为您关闭它们:

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)

#2


13  

Just use for x in f: ..., this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip call because the trailing newline is already stipped.

只需在f:...中使用x,这会给你一行一行,更短和可读(部分原因是它在文件结束时自动停止)并且还保存了rstrip调用,因为已经规定了尾部换行符。

The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline will return an empty string, not None. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue makes the code ignore blank lines, which is propably a good thing anyway.

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

#3


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

#4


2  

You should learn about EAFP vs LBYL.

您应该了解EAFP与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:]))

#5


1  

This is probably because an empty line at the end of your input file.

这可能是因为输入文件末尾有一个空行。

Try this:

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

#1


57  

The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this:

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

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)

On the other hand it would be better to use for x in f instead of readline. Do not forget to close your files or better to use with that close them for you:

另一方面,最好在f中使用x而不是readline。不要忘记关闭您的文件或更好地使用它们为您关闭它们:

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)

#2


13  

Just use for x in f: ..., this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip call because the trailing newline is already stipped.

只需在f:...中使用x,这会给你一行一行,更短和可读(部分原因是它在文件结束时自动停止)并且还保存了rstrip调用,因为已经规定了尾部换行符。

The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline will return an empty string, not None. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue makes the code ignore blank lines, which is propably a good thing anyway.

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

#3


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

#4


2  

You should learn about EAFP vs LBYL.

您应该了解EAFP与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:]))

#5


1  

This is probably because an empty line at the end of your input file.

这可能是因为输入文件末尾有一个空行。

Try this:

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