mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-05-05 14:28:31 +00:00
Merge pull request #4409 from TanayParikh/patch-1
[python/en] Python Update `open` File Open `mode`
This commit is contained in:
commit
c45730e144
@ -501,20 +501,20 @@ with open("myfile.txt") as f:
|
|||||||
|
|
||||||
# Writing to a file
|
# Writing to a file
|
||||||
contents = {"aa": 12, "bb": 21}
|
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
|
file.write(str(contents)) # writes a string to a file
|
||||||
|
|
||||||
import json
|
import json
|
||||||
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
|
file.write(json.dumps(contents)) # writes an object to a file
|
||||||
|
|
||||||
# Reading from 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
|
contents = file.read() # reads a string from a file
|
||||||
print(contents)
|
print(contents)
|
||||||
# print: {"aa": 12, "bb": 21}
|
# 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
|
contents = json.load(file) # reads a json object from a file
|
||||||
print(contents)
|
print(contents)
|
||||||
# print: {"aa": 12, "bb": 21}
|
# print: {"aa": 12, "bb": 21}
|
||||||
|
Loading…
Reference in New Issue
Block a user