Writing and reading
with open("notes.txt", "w") as file: # "w" writes over the file
file.write("Line one\n")
file.write("Line two\n")
with open("notes.txt", "a") as file: # "a" adds to the end
file.write("Line three\n")
with open("notes.txt") as file: # Reading is the default
for line in file:
print(line.strip())Output
Line one Line two Line three
CSV files
import csv
with open("marks.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["name", "marks"])
writer.writerow(["Riya", 78])
writer.writerow(["Aman", 92])
with open("marks.csv") as file:
for row in csv.DictReader(file):
print(row["name"], "scored", row["marks"])Output
Riya scored 78 Aman scored 92
import os
with open("temp.txt", "w") as file:
file.write("hello")
print(os.path.exists("temp.txt"))
os.remove("temp.txt")
print(os.path.exists("temp.txt"))Output
True False
Finished reading?