How to iterate over the file in python

前端 未结 5 1119
一向
一向 2020-11-29 04:49

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

5条回答
  •  没有蜡笔的小新
    2020-11-29 05:35

    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:

    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)
    

提交回复
热议问题