Connecting Tech Pros Worldwide Help | Site Map

Reading a specific line in a text file

Newbie
 
Join Date: Apr 2009
Location: Leiden, Netherlands
Posts: 2
#1: Apr 28 '09
Hi,

I need a help regarding reading a line in a text file. I have some files with columns but some header information at the top. Some of these header lines begin with a *, and some of them with nothing. I have to read the 9th line and 5th column, then extract the number from here and save it to another text file.

I was thinking of some solutions.
1) I can delete the first 8 lines and read the columns straightforward.
2) I first read the 9th line and then the 5th column, by using f.readline() or etc. However, readline only reads the first line and I could not tell to read the 9th line.

I could not made neither of those solutions. The second would be much better because at the end I do not lose the header info. I have hundreds of these files, any help would be much appreciated.

Thanks
micmast's Avatar
Familiar Sight
 
Join Date: Mar 2008
Location: Belgium
Posts: 136
#2: Apr 28 '09

re: Reading a specific line in a text file


you could read the entire file in an array and use that array like this
array[8]
and continue from there on out
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,560
#3: Apr 28 '09

re: Reading a specific line in a text file


micmast's suggestion should work by using file method f.readlines(). List index 0 is your header and index 8 is your line of data. Assuming the separator is a comma:
Expand|Select|Wrap|Line Numbers
  1. f = open(file_name)
  2. fileList = f.readlines()
  3. f.close()
  4. fifth_column = fileList[8].split(',')[4]
Newbie
 
Join Date: Apr 2009
Location: Leiden, Netherlands
Posts: 2
#4: Apr 28 '09

re: Reading a specific line in a text file


Great, it is working perfectly.

Thanks a lot...
Reply

Tags
delete lines, python, read lines