AppDividend
Latest Code Tutorials

Python open() Example | File open() Function In Python

0

Python open() Example | File open() Function In Python is today’s topic. The open() function opens the file and returns it as a file object. It is used in the file handling process. Python 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 FileNotFoundError exception.

Python open() Example

File handling in Python requires no importing of modules. Python open() is built-in function.

The syntax of the open() function is following.

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. Opens the file for reading, error if the file does not exist.

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

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

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

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

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

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

 

#How to open a file in Python

Let’s create 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 which 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

#Close file

We can close the opened file using the close() function.

# 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

Finally, Python open() Example | File open() Function In Python is over.

Leave A Reply

Your email address will not be published.

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