write to specific line in file?
castironpi
castironpi at gmail.com
Fri May 16 18:22:34 EDT 2008
On May 16, 2:25 pm, 7stud <bbxx789_0... at yahoo.com> wrote:
> 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.
Some options:
1. Limit line length. Then offset is ( line* length ).
2. Name your relation.
3. Hijack the operating system. Remember:
abc
def
on disk looks like
abc\ndef
where
abcd
def
looks like
abcd\ndef
So, if you want line 2, you have to scan line 1.
More information about the Python-list
mailing list