Writing to a certain line?

bruno at modulix onurb at xiludom.gro
Tue Jun 6 04:49:08 EDT 2006


Tommy B wrote:
> I was wondering if there was a way to take a txt file and, while
> keeping most of it, replace only one line.

<meta>
This is a FAQ (while I don't know if it's in the FAQ !-), and is in no
way a Python problem. FWIW, this is also CS101...
</meta>

You can't do this in place with a text file (would be possible with a
fixed-length binary format).

The canonical way to do so - whatever the language, is to write the
modified version in a new file, then replace the old one.

import os
old = open("/path/to/file.txt", "r")
new = open("/path/to/new.txt", "w")
for line in old:
  if line.strip() == "Bob 62"
    line = line.replace("62", "66")
  new.write(line)
old.close()
new.close()
os.rename("/path/to/new.txt", "/path/to/file.txt")

If you have to do this kind of operation frequently and don't care about
files being human-readable, you may be better using some lightweight
database system (berkeley, sqlite,...) or any other existing lib that'll
take care of gory details.

Else - if you want/need to stick to human readable flat text files - at
least write a solid librairy handling this, so you can keep client code
free of technical cruft.

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list