mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-08-29 01:21:07 +02:00
Python Update open
File Open mode
Per https://docs.python.org/3.7/library/functions.html#open, the `+` is for `open a disk file for updating (reading and writing)`. Per the example, if we're looking to just read/write, the `+` isn't necessary.
This commit is contained in:
@@ -492,19 +492,19 @@ with open("myfile.txt") as f:
|
||||
|
||||
# Writing to a file
|
||||
contents = {"aa": 12, "bb": 21}
|
||||
with open("myfile1.txt", "w+") as file:
|
||||
with open("myfile1.txt", "w") as file:
|
||||
file.write(str(contents)) # writes a string to a file
|
||||
|
||||
with open("myfile2.txt", "w+") as file:
|
||||
with open("myfile2.txt", "w") as file:
|
||||
file.write(json.dumps(contents)) # writes an object to a file
|
||||
|
||||
# Reading from a file
|
||||
with open('myfile1.txt', "r+") as file:
|
||||
with open('myfile1.txt', "r") as file:
|
||||
contents = file.read() # reads a string from a file
|
||||
print(contents)
|
||||
# print: {"aa": 12, "bb": 21}
|
||||
|
||||
with open('myfile2.txt', "r+") as file:
|
||||
with open('myfile2.txt', "r") as file:
|
||||
contents = json.load(file) # reads a json object from a file
|
||||
print(contents)
|
||||
# print: {"aa": 12, "bb": 21}
|
||||
|
Reference in New Issue
Block a user