write to specific line in file?

7stud bbxx789_05ss at yahoo.com
Fri May 16 15:25:34 EDT 2008


globalrev wrote:
> i ahve a program that takes certain textsnippets out of one file and
> inserts them into another.
>
> problem is it jsut overwrites the first riow every time.
>
> i want to insert every new piece of text into the next row.
> so:
> 1. how do i write to a new line every time i write to the file?
>
> 2. if i dont want to write to a new line but just want to insert it
> after the last token in the file, how do i do then?

Generally, you can't "insert" anything into a file.  You can either
append to the end of a file, or you can rewrite the whole file.  It
sounds like you probably want to read the file into an array using
readlines().  Then manipulate that array however you want--appending
and inserting--and when you are done, overwrite the file with your
array.

However, you should be aware that as soon as you open a file for
writing all the data is erased, and if your program should happen to
crash right then, the array containing the data will disappear into
the ether and your file will be empty--in other words all your data
will be gone.  To prevent such an occurence, you should write your
final data to another file, then delete the original file, and finally
change the other file's name to the original file name.




More information about the Python-list mailing list