Skip to main content

7/10 Write or Create file

<..>

Both write and create uses same open() with 3 main flags:

  • a - append to existing file (or create if doesn't exist)
  • w - write to file (or overwrite if it exists)
  • x - create only (error if file exists)

If encoding is not defined it would change depending on platform.

Ideally writing should be done with with - it ensures files are closed properly, doesn't matter how logic flows or if any exceptions are raised.


Write

Append to file
with open('filename.txt', 'a', encoding="utf-8") as f:
    f.write("One more row goes here")

or basic (no with, no encoding):

f = open("filename.txt", "a")
f.write("One more row goes here")
f.close()
Over(write) file
with open('ilename.txt', 'w', encoding="utf-8") as f:
    f.write("File {filename.txt} contains only this line")

or basic (no with, no encoding):

f = open("filename.txt", "w")
f.write("File {filename.txt} contains only this line")
f.close()


Create

create empty file

f = open("filename.txt", "x")
f.close()

Other

Python docs: here