Skip to content
techsnow

Files & Errors

Reading and Writing Files

# write (creates or overwrites)
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Line one\n")
    f.write("Line two\n")

# append
with open("notes.txt", "a", encoding="utf-8") as f:
    f.write("Line three\n")

# read line by line
with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

Output

Line one
Line two
Line three
ModeMeaning
"r"Read (default)
"w"Write, replacing the file
"a"Append to the end
"x"Create; error if it exists