Python path and append

Steven D'Aprano steve at pearwood.info
Mon Apr 25 21:51:23 EDT 2016


On Tue, 26 Apr 2016 05:00 am, Seymore4Head wrote:

> I was reading that.  I have read it before.  I don't use python enough
> to even remember the simple stuff.  Then when I try to use if for
> something simple I forget how.

It is perfectly fine to forget things that you read weeks or months before.
The point is, having forgotten it, you should go back and refresh your
memory when you need to.


> f = open('wout.txt', 'r+')
> for line in f:
>     line=line.strip()
>     f.write(line+" *")
> f.close()
> 
> Still broke.  How about just telling me where I missed?  Please?

The contents of files don't just magically get moved out of the way when you
write to them. There is no "insert mode" for files -- they are always set
to "overwrite" mode. (Possible a few very old operating systems on
supercomputers from the 1970s or 80s may have supported inserting... I seem
to recall that VMS may have allowed that... but don't quote me.)

So you can append to the *end* of a file without disrupting the content, but
you cannot insert to the middle or beginning of a file without overwriting.

The basic way to insert data into a file is:

* read the entire file into memory;
* insert the new data into the memory;
* write the entire file out again.



with open("myfile.txt") as f:
    lines = f.readlines()

for i, line in enumerate(lines):
    lines[i] = line.strip() + " *\n"  # space, asterisk, newline

with open("myfile.txt", "w") as f:
    f.writelines(lines)


That's good enough for DIY or hobby use. But for professional use, it starts
getting *very* complex quickly. What if the power goes off or your computer
crashes half-way through writing the file? You've lost all your data.

See here for the *start* of a more professional approach:

http://code.activestate.com/recipes/579097-safely-and-atomically-write-to-a-file/


-- 
Steven




More information about the Python-list mailing list