the full guide

Reading and writing files

Save results, read data line by line, and handle CSV files.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

Writing and reading

files.py
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

csv_demo.py
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
file_check.py
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?