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.

Examples

>>> 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 = spam.read()
...     print(content)
# My first line
#
# My second line

Subscribe to pythoncheatsheet.org

A bullshit free publication, full of interesting, relevant links.