1

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.

Exemple:

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()

Then, I would like to modify the content of the line:

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 :

IndexError: list index out of range

I tried many format types but unfortunately it still not working. Do you have some tips :)

Thank you.

Licia
  • 55
  • 4
  • 1
    I have a couple of tips. 1. Check `lines_runD`'s length. 2. Use `{0}` for format strings, not `%s`. – erip Jun 24 '16 at 15:19
  • Yes I tried it also. It's not working unfortunately, I still have the same error – Licia Jun 27 '16 at 08:18

1 Answers1

1

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

Luis
  • 3,327
  • 6
  • 35
  • 62