open() / Files (Python)

open() is the built-in function for reading from and writing to files. You give it a filename and a mode ('r' to read, 'w' to write, 'a' to append).

Python

Best practice is to use open() together with a with statement so the file closes automatically. You read content with .read() or by looping over the file line by line.

Syntax

open(filename, mode)

Examples

Python

with open("data.txt", "w") as f:
    f.write("line one\n")

with open("data.txt") as f:
    print(f.read().strip())

Output:

line one

Learn it in a lesson

See also

Back to the Dictionary