summaryrefslogtreecommitdiffhomepage
path: root/python3.html.markdown
diff options
context:
space:
mode:
authorDivay Prakash <divayprakash@users.noreply.github.com>2019-08-25 00:15:14 +0530
committerGitHub <noreply@github.com>2019-08-25 00:15:14 +0530
commit88223544ce093ee3409122e670418c6057c57b18 (patch)
tree13a22756e750eea90a9aeecaf2cca3812ca356c5 /python3.html.markdown
parentf035528cebb54dd6a8be276af56b338b3ceed8c9 (diff)
parent77ab89a4b3ead12172230781e61bed629e12f7b5 (diff)
Merge pull request #3610 from Blandry1/master
[Python3/en] Added write to and read from a file syntax
Diffstat (limited to 'python3.html.markdown')
-rw-r--r--python3.html.markdown20
1 files changed, 20 insertions, 0 deletions
diff --git a/python3.html.markdown b/python3.html.markdown
index ef78ce37..4cabb27b 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -505,6 +505,26 @@ with open("myfile.txt") as f:
for line in f:
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.
# An iterable is an object that can be treated as a sequence.
# The object returned by the range function, is an iterable.