Python open: How to Open a File in Python

The open() function opens the file (if possible) and returns the corresponding file object. File handling in Python requires no importing of modules.

Python open

Python open() is a built-in function that opens the file and returns it as a file object. It is used in the file handling process.

The open() function returns the file object, which can be used to read, write, and modify the file. If a file is not found, then it raises the FileNotFoundError exception.

Syntax

open(file, mode)
Parameter Description
file The path and name of a file.
mode The string, define which mode you want to open the file in:

“r” – Read – Default value. It opens the file for reading; error if the file does not exist.

“a” – Append – Opens the file for appending and creates the file if it does not exist.

“w” – Write – Opens the file for writing and creates a file if it does not exist.

“x” – Create – Creates a specified file, and returns an error if the file exists.

Also, you can specify if a file should be handled in binary or text mode.

“t” – Text – Default value. Text mode.

“b” – Binary – Binary mode (e.g. images).

 

How to open a file in Python

To open a file in Python, use the open() function. The open() function accepts file and various modes that can help you while opening a file.

Let’s create an app.txt file in the same directory as our app.py file.

Now, inside the app.py file, write the following code.

f = open("app.txt")
print(f)

See the output.

➜  pyt python3 app.py
<_io.TextIOWrapper name='app.txt' mode='r' encoding='UTF-8'>
➜  pyt

Since the mode is omitted, the file is opened in ‘r’ mode; it opens for reading.

Providing mode to open()

Let’s pass the ‘r’ mode as a parameter and see the output.

# app.py

f = open("app.txt", 'r')
print(f)

It will give us the same output as above.

Python has an encoding system that is platform-dependent. Hence, it’s recommended to specify an encoding type if you are working in the text mode.

f = open("path_to_file", mode = 'r', encoding='utf-8')

Let’s pass the ‘w’ mode. The ‘w‘ stands for writing mode.

f = open("app.txt", 'w')
print(f)

See the output.

➜  pyt python3 app.py
<_io.TextIOWrapper name='app.txt' mode='w' encoding='UTF-8'>
➜  pyt

Let’s pass the ‘a’ mode. The ‘a’ stands for append mode.

f = open("app.txt", 'a')
print(f)

See the output.

➜  pyt python3 app.py
<_io.TextIOWrapper name='app.txt' mode='a' encoding='UTF-8'>
➜  pyt

How to close a file in Python

To close a file in Python, use the file.close() function. The file.close() is a built-in function that closes the opened file. A closed file cannot be read or written anymore.

# app.py

f = open("app.txt", 'r')
print('File is opened')
f.close()
print('File is closed')

See the output.

➜  pyt python3 app.py
File is opened
File is closed
➜  pyt

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.