I'm a newbie in python. I'm currently trying to modify a line in a file, this after catching this line by using linecache.
run_D = open('toto.dat','r')
lines = run_D.readlines()
print "Name of the file: ", run_D.name
seq=["%s'retrieve'"]
line_1 = linecache.getline('toto.dat', 51)
lines_runD = run_D.readlines()
run_D.close()
lines_runD[50]="%s !yop \n".format(seq) #--> this part seems not working
fic = open('toto.dat','w')
fic.writelines(lines_runD)
fic.close()
I have this error :
I tried many format types but unfortunately it still not working. Do you have some tips :)
Thank you.
I think you mix two things: linecache
and readlines
.
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
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( )
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 )
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?