I think you mix two things: linecache
and readlines
.
1. linecache
From the docs:
The linecache module allows one to get any line from any file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file.
That means, you can read the line number 51 with linecache
very easily:
import linecache
line_1 = linecache.getline('toto.dat', 51)
print line_1
2. readlines
You can achieve the same with the following code:
f = open( 'toto.dat' )
flines = f.readlines()
f.close( )
print flines[50]
And then, you can modify the line number 51 as follows:
flines[50] = ' new incoming text!\n '
f = open( 'toto.dat', 'wt' )
for l in flines:
f.write(l)
f.close( )
2.x. with
The with statement makes it easier and safer to work with files, because it takes care of closing it for you.
with open( 'toto.dat', 'r' ) as f:
flines = f.readlines()
print flines[50]
with open( 'toto.dat', 'wt' ) as f:
for l in flines:
f.write( l )
* Recommendations
Note that these methods are low level and recommended for either learning the basics or coding more complicated functions, once you really know what you are doing. Python offers a lot of input-output libraries, with many useful features. Just make a search for them and you sure get some nice examples.
Check for instance the following questions for further learning:
How do I modify a text file in Python?
Search and replace a line in a file in Python
Open files in 'rt' and 'wt' modes