Use Python’s built-in open() to access a file. Its first argument is a pathname; the result is a file object, not the file’s contents. Read or write through that object’s methods. section 13.1
Choose the second argument to control access:
- Use 'r' to read. It is the default when no mode is given. section 13.3
- Use 'w' to write, erasing existing contents, or 'a' to append after existing contents. section 13.3
Write, then read
with open('myfile', 'w') as file_object: file_object.write('Hello, World\n') with open('myfile', 'r') as file_object: line = file_object.readline() write() needs an explicit newline in its string. readline() returns the line, including its newline if present. Using with is generally preferred because it better manages potential I/O errors. section 13.1 section 13.3 section 13.4
A relative pathname such as 'myfile' refers to the current working directory; an absolute pathname can locate a file elsewhere. os.path.join() constructs paths according to the operating system’s conventions. For text files, open() also accepts options for encoding, newline handling, and decoding errors; binary mode instead processes bytes. section 13.1 section 13.3 section 13.11 section 21.2.1








