mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-11-26 09:21:00 +03:00
Merge pull request #3610 from Blandry1/master
[Python3/en] Added write to and read from a file syntax
This commit is contained in:
commit
88223544ce
@ -505,6 +505,26 @@ with open("myfile.txt") as f:
|
|||||||
for line in f:
|
for line in f:
|
||||||
print(line)
|
print(line)
|
||||||
|
|
||||||
|
# Writing to a file
|
||||||
|
contents = {"aa": 12, "bb": 21}
|
||||||
|
with open("myfile1.txt", "w+") as file:
|
||||||
|
file.write(str(contents)) # writes a string to a 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:
|
||||||
|
contents = file.read() # reads a string from a file
|
||||||
|
print(contents)
|
||||||
|
# print: {"aa": 12, "bb": 21}
|
||||||
|
|
||||||
|
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}
|
||||||
|
|
||||||
|
|
||||||
# Python offers a fundamental abstraction called the Iterable.
|
# Python offers a fundamental abstraction called the Iterable.
|
||||||
# An iterable is an object that can be treated as a sequence.
|
# An iterable is an object that can be treated as a sequence.
|
||||||
# The object returned by the range function, is an iterable.
|
# The object returned by the range function, is an iterable.
|
||||||
|
Loading…
Reference in New Issue
Block a user