How do you append to the file instead of writing in same line with new line.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
You need to open the file in append mode, by setting "a" or "ab" as the mode. See open().
When you open with "a" mode, the write position will always be at the end of the file (an append). You can open with "a+" to allow reading, seek backwards and read (but all writes will still be at the end of the file!).
Example:
Note: Using 'a' is not the same as opening with 'w' and seeking to the end of the file - consider what might happen if another program opened the file and started writing between the seek and the write. On some operating systems, opening the file with 'a' guarantees that all your following writes will be appended atomically to the end of the file (even as the file grows by other writes).
A few more details about how the "a" mode operates (tested on Linux only). Even if you seek back, every write will append to the end of the file:
In fact, the
fopen
manpage states:Old simplified answer (not using
with
):Example: (in a real program use
with
to close the file - see the documentation)You probably want to pass
"a"
as the mode argument. See the docs for open().There are other permutations of the mode argument for updating (+), truncating (w) and binary (b) mode but starting with just
"a"
is your best bet.