Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
python3
file handling
file reading

How to open files in Python

Educative Answers Team

open() is a built-in function used for file handling in Python.

svg viewer

Syntax

open(file, mode)

  • file: path and name of the file
  • mode: specifies the mode in which the file is opened
Mode Meaning
r reading
w writing (truncating if file already exists)
a appending
x creating (returns error if file already exists)
+ updating (reading and writing)
t text mode
b binary mode

Note: mode defaults to ‘rt’ (reading in text mode)

open() returns a file object. If the file cannot be opened, an OSError is raised.
You can use functions read() and write() on the file object to, you guessed it, read and write content.

Code

Below is an example of how to use open() for file handling.

main.py
example.txt
# Opening file to read text (default mode: read)
with open("example.txt", 'r') as my_file:
    content = my_file.read()    # read() returns the content of file
    print("Reading file: ")
    print(content)

# Opening file to write text (overwrites previous content)
with open("example.txt", 'w') as my_file:
    my_file.write("Replaced text!")     # write() writes passed content to file

# Opening file to append text
with open("example.txt", 'a') as my_file:
    my_file.write(" Added more text!")   # write() writes passed content to file

# Opening file to read in binary mode
with open("example.txt", 'rb') as my_file:
    content = my_file.read()    # read() returns the content of file
    print("Reading file after replacing the previous text and appending to it: ")
    print(content)

For more details about how open() works, you can refer to the official docs.

RELATED TAGS

python
python3
file handling
file reading
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring