Codzy

Reading and writing files

The open() function opens a file. The second argument is the mode: "r" to read (the default), "w" to write (the content is erased) and "a" to append at the end.

Use with open(...) as f:: the file is closed automatically at the end of the block. f.read() reads the whole content, f.write() writes text, and a for loop reads the file line by line. Here, files are created in a temporary space inside your browser.

with open("notes.txt", "w") as f:
    f.write("Line 1\n")
    f.write("Line 2\n")

with open("notes.txt", "a") as f:
    f.write("Line 3\n")

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

Start the lesson