-
-
Save azamsharp/053e6cf659b13dea2d97f44f0beb2db4 to your computer and use it in GitHub Desktop.
Reading and Writing Files Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
filename = "helloworld.txt" | |
# reading the whole file at once | |
with open(filename) as file_object: | |
contents = file_object.read() | |
print(contents) | |
print("READING LINE BY LINE") | |
# reading the file line by line | |
with open(filename) as file_object: | |
lines = file_object.readlines() | |
print(lines) | |
for line in lines: | |
print(line.rstrip('\n')) | |
# writing a file | |
with open('filetowrite.txt','w') as file_object: | |
file_object.write('Bye World. I am using Python to write a file') | |
# appending file | |
with open('appendingToFile.txt','a') as file_object: | |
file_object.write('Bye World') | |
file_object.write('\n') | |
# Writing JSON to a file using json.dump | |
with open('users.json','w') as file_object: | |
dictionary = {'firstname':'John','lastname':'Azam'} | |
json.dump(dictionary,file_object) | |
# reading JSON from file using json.load | |
with open('users.json') as file_object: | |
dictionary = json.load(file_object) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment