Last active
June 17, 2022 10:42
-
-
Save madan712/f05318a3f95eda0bc40bed795ba9e96c to your computer and use it in GitHub Desktop.
Python - Read and write a text file
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
def write_file(): | |
print("Writing a file..") | |
try: | |
f = open("my_file.txt", "a") | |
for num in range(100): | |
f.write("Line " + str(num) + "\n") | |
f.close() | |
except Exception: | |
print("Could not write to file") | |
def read_file(): | |
print("Now reading the file..") | |
try: | |
f = open("my_file.txt", "r") | |
for line in f.readlines(): | |
print(line) | |
f.close() | |
except Exception: | |
print("Could not read to file") | |
write_file() | |
read_file() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment