open()

The built-in function that opens a file by name and returns a file object, for reading by default or for writing or appending.

In more detail

open("notes.txt", "w") creates or empties the file; open("notes.txt") reads it. A relative name is looked up in the current working directory, so a program run from another folder may not find its files. Pass encoding="utf-8" to get the same result on every system.

Example

with open("out.txt", "w", encoding="utf-8") as f:
    f.write("hi\n")

Related terms

Taught in

References

Certification courses