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.

Introduction

The open() function in Python is used to open a file and returns a file object. It’s the standard way to interact with files on your system. You can specify the mode for opening the file, such as read, write, or append.

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

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