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
To iterate through lines in a file using Python, you can loop over each line in a file with a simple for loop. When reading files, the ability to read files sequentially line by line can be very useful. Reading text from a file is easy with the Python open() function.
Method 1: Read a File Line by Line using readlines() This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines. We can iterate over the list and strip the newline '\n' character using strip() function. Example: Python3.
Many things in Python are iterables, but not all of them are sequences. An iterator is an object representing a stream of data. It does the iterating over an iterable. You can use an iterator to get the next value or to loop over it.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With