Re: Writing to a certain line?



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@xxxxxxxxxxx'.split('@')])"
.



Relevant Pages

  • Re: Switch() Statement Not Working
    ... This is recommended in the FAQ only because all other books are worse. ... Because it is the FAQ of _this_ newsgroup, written by and contributed to by ... I do not care much about your real name, at least not in this NetNews ... acceptable as there is no .house top-level domain. ...
    (comp.lang.javascript)
  • Re: help with document height/width
    ... clientWidth. ... This is not a help desk, so I don't particularly care what oversensitive ... Document objects have no height as they have no graphical representation. ... By reading the FAQ and following its recommendations. ...
    (comp.lang.javascript)
  • Re: SATA hotplug from the user side ?
    ... So, no, you don't really have to care. ... but then this really should be in the SATA hotplug FAQ (or can one ... Care to submit patch to FAQ to Jeff? ... I think this is best solved by udev. ...
    (Linux-Kernel)
  • Re: MTA experts: address rewriting depending on next hop
    ... word if you care, maybe you can prove that Exim's FAQ 805 or 807 iirc ... the link is on d-d - is wrong. ...
    (Debian-User)
  • Re: Taking a little time off, I think
    ... day is the people who's only measure of their self-worth is how ... So the point of life is to stay in a good "mood" and never to feel ... And if it's not covered in the FAQ, ... And I don't care that you don't care! ...
    (rec.food.cooking)