On Dec 20, 7:56 pm, Horacius ReX <horacius....@gmail.comwrote:
Hi, sorry but after looking for information, I still did not get how,
when reading a text file in python, can one jump to a concrete line
and then read the different data (separated by spaces). In each line
there is different number of columns so sometimes i get kind of "index
out" error. Is there a better way to read the different data on each
row and avoiding to know the exact number of columns ?
Thanks
If you are working with a file that is of a fixed length you can use
the .seek() function
ie. 500 characters per line, and a newline character is an additional
one then for the 10th line you would do:
file_input.seek(5010, 0)
file_input.readline()
If it is not a fixed length file you can do:
line_to_seek = 9 # for the 10th line, you need to look for num9 as
counting starts @ 0
for (i, line) in enumerate(file_input):
if i == line_to_seek:
.... process the line
As for combatting the issue of lack of data on a line, do something
like:
line_contents = line.split(' ')
if len( line_contents ) = required_elements:
.... do something
else:
.... print 'failed'