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.
- If exist, open and read it.
- 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, anyseek()operations will be undone/ignore at the next write.
Difference between modes a, a+, w, w+, and r+ in built-in open function?
Python open file mode table