2

I want to read a text file line by line. I found how to read line by line by searching but not how to call a specific line in a text file. Basically, i want to do something with particular lines( like the first line, the second line, the third line, etc):

if particular_line is something:
....

Also, how can i do something like this:

if return_from_another_function in file:
....

Basically, i want an example of how i could do that if it's possible.

Bach
  • 6,145
  • 7
  • 36
  • 61

3 Answers3

2
f = open('filename', 'r')
lines = f.readlines()

now you get a list type object lines which you can use to access particular line or iterate and search for particular line.

salmanwahed
  • 9,450
  • 7
  • 32
  • 55
1

The standard linecache module makes this a snap:

import linecache
theline = linecache.getline(thefilepath, desired_line_number)

For your second que (from Ans):

If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):

if 'blabla' in open('example.txt').read():
    print "true"
Community
  • 1
  • 1
a.m.
  • 2,083
  • 1
  • 16
  • 22
1

Probably this will help:

myfile = open(filename, "rb", 0)
for line in myfile
   if(line is "your string to be compared")
       print "do something here" 
Gaurav Kumar
  • 153
  • 10