Skip to content

Instantly share code, notes, and snippets.

@liviaerxin
Last active March 8, 2023 06:50
Show Gist options
  • Save liviaerxin/26bac18a42dd7fe0a9e58142f179dd9d to your computer and use it in GitHub Desktop.
Save liviaerxin/26bac18a42dd7fe0a9e58142f179dd9d to your computer and use it in GitHub Desktop.
Python `open()` file mode for read/write, create?, and truncat? #python

Open() File Mode In Python

Here's a table of modes:

r r+ w w+ a a+
read + + + +
write + + + + +
write after seek + + +
create + + + +
truncate + +
position at start + + + +
position at end + +

When open file in python,

with open("file.txt", "r+") as f:
  f.readline()

A treat that: You want to read a file but it does not know whether it exists, and if not exist, you want to create it but not truncate it if it exist.

  1. If exist, open and read it.
  2. If not, creat the file and read empty content out or give some initial value.

code as,

try:
  # file exists, open and read it.
  with open("file.txt", "r+") as f:
    #f.seek(0) # seek to the first char since we open as appending
    read_result = f.readline()
    print(read_result)
except FileNotFoundError as e:
  # file not exists, give some initial value
  with open("file.txt", "w+") as f:
    f.write("some initial value")

Note: 'a' or 'a+' always ignore, any seek() operations will be undone/ignore at the next write.

References

Difference between modes a, a+, w, w+, and r+ in built-in open function?
Python open file mode table

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment