Back

File I/O

File I/O means reading from and writing to files. Python's open() gives you a file object, and using it with 'with' closes the file automatically when you're done. Modes: 'r' read, 'w' write (overwrites), 'a' append.

# Write (creates or overwrites the file)
with open("notes.txt", "w") as f:
    f.write("First line\n")

# Append
with open("notes.txt", "a") as f:
    f.write("Second line\n")

# Read the whole file
with open("notes.txt", "r") as f:
    print(f.read())

# Read line by line
with open("notes.txt") as f:
    for line in f:
        print(line.strip())

Roadmap