Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over the file in python

Tags:

python

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

like image 878
user567879 Avatar asked Apr 20 '11 16:04

user567879


People also ask

How do I iterate over a file?

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.

How do you traverse a line by line in Python?

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.

What is iterate over in Python?

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.


1 Answers

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) 
like image 103
joaquin Avatar answered Sep 23 '22 11:09

joaquin