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

# Opens a brand new file (in 'x' mode will throw if already exists)
spam = open('spam.txt', mode='x')
spam.write('My first line\n\n')
spam.close()
# Appends to file and automatically closes afterward
with open('spam.txt', mode='a') as spam:
    spam.write('My second line')
with open('spam.txt') as spam:
    content = spam.read()
    print(content)
My first line

My second line