[Tutor] how to write a string into a specific line in a file
Alan Gauld
alan.gauld at freenet.co.uk
Tue Mar 7 12:18:27 CET 2006
> I was wondering if it is possible to write a string to a specific line
> in a file without reading in the whole file in as the below.
Some languages, such as COBOL and some BASICs etc support
random access files, unfortunately Python doesn't (Although I'll be
amazed if somebody hasn't cooked up (or is cooking up) a module
that does it)
> f = open(filename)
> lines = f.readlines()
> f.close()
> # num for some line number
> line[num] = "String"
> f = open(filename)
> f.writelines(lines)
> f.close()
You can shorten that slightly to
lines = open(filnemame).readlines()
lines[num] = 'foo'
open(filename).write('\n'.join(lines))
But essentially that is the standard way to do it.
You can avoid reading the entire file by
using seek() to go to a specific location in the file.
You can also write directly to the file but that is dangerous
unless you are writing exactly the same number of bytes as
previously existed. (And you can force that by defining a
fixed record structure - which is how ISAM files work in
BASIC/COBOL etc).
> Or would the best way to do line replacement be through iteration.
> for line in open(filename):
> # write to current line???
This is ok if you open for both reading and writing...
Also using enumerate will give you the line number to check.
Alan G
More information about the Tutor
mailing list