Skip to content

Instantly share code, notes, and snippets.

@madan712
Last active June 17, 2022 10:42
Show Gist options
  • Save madan712/f05318a3f95eda0bc40bed795ba9e96c to your computer and use it in GitHub Desktop.
Save madan712/f05318a3f95eda0bc40bed795ba9e96c to your computer and use it in GitHub Desktop.
Python - Read and write a text file
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