YoungBoi
YoungBoi

Reputation: 15

How to stop Python rewriting files?

Is there a way to stop Python rewriting files?

For example, when I run code once, it writes number "1" in text file. If I run same code tommorow, it won't erase that 1 from yesterday, it will add one more "1", so it should look like this:

1

1

My would look like this:

file = open("filename","w")
file.write(str(1) + "\n)
file.close()

If someone can tell me where is my mistake, please help me.

Thank you in advance !

Upvotes: 0

Views: 328

Answers (1)

abarnert
abarnert

Reputation: 365707

If you read the docs for open, that second parameter that you're passing a "w" to is the mode:

mode is an optional string that specifies the mode in which the file is opened. It defaults to 'r' which means open for reading in text mode. Other common values are 'w' for writing (truncating the file if it already exists), 'x' for exclusive creation and 'a' for appending…

And then there's a handy chart of all of the mode characters, which reiterates the same information:

  • 'w': open for writing, truncating the file first
  • ...
  • 'a': open for writing, appending to the end of the file if it exists

So, just use "a" instead of "w", and Python will add your new line to the end of the file, instead of truncating the file to nothing and then adding your new line to that now-empty file.


It's probably worth knowing that this is very closely based on the behavior of the fopen function from C and POSIX—which many other languages have also copied. So, in almost any language you run into, if there's a w mode for writing that overwrites the file, there's probably also an a mode for appending.

Upvotes: 1

Related Questions