Python open() built-in function

From the Python 3 documentation

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised. See Reading and Writing Files for more examples of how to use this function.


>>> spam = open('spam.txt', mode='x')
>>> spam.write('My first line\n\n')
>>> spam.close()
# Opens a brand new file (in 'x' mode will throw if already exists)

>>> with open('spam.txt', mode='a') as spam:
...     spam.write('My second line')
# Appends to file and automatically closes afterward

>>> with open('spam.txt') as spam:
...     content =
...     print(content)
# My first line
# My second line

Subscribe to

Join 10.900+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.