open
Open a file for reading or writing.
Python 3.13
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)- =default value
- file
- The path to the file or a file descriptor number.str | PathLike | int
- mode
- The open mode, 'r' by default; letters combine, such as 'rb' or 'a+'.strOptional'r''w''a''x''b''t''+'
- buffering
- Buffering: -1 for the default, 0 for no buffer (binary mode only), 1 for line buffering (only when writing in text mode), more than 1 for the buffer size in bytes.intOptional
- encoding
- The encoding of a text file, such as 'utf-8'; the default depends on the system.str | NoneOptional
- errors
- How to handle encoding errors; None by default, which works like 'strict' and raises an error.str | NoneOptional'strict''ignore''replace''backslashreplace''surrogateescape'
- newline
- The line ending in text mode; None by default, which turns any line ending into '\n' when reading.str | NoneOptionalNone'''\n''\r''\r\n'
- closefd
- If False and file is a descriptor, it stays open when the file is closed.boolOptional
- opener
- A custom function to open the file; rarely needed.Callable | NoneOptional
Return value
A file object; close it with close() or use with.
Examples
Writing and reading a file
Python 3.13
with open('file.txt', 'w', encoding='utf-8') as f:
f.write('hello')
with open('file.txt', encoding='utf-8') as f:
print(f.read())hello
Appending to the end of a file
Python 3.13
with open('log.txt', 'w', encoding='utf-8') as f:
f.write('first\n')
with open('log.txt', 'a', encoding='utf-8') as f:
f.write('second')
with open('log.txt', encoding='utf-8') as f:
print(f.read())first second
Details
Pass encoding='utf-8' so that a text file reads the same on every system. When writing with newline=None, the '\n' character is replaced with the system line separator os.linesep, while with '' or '\n' it stays as is.
