Trusted answers to developer questions

How to open files in Python

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Python is a high-level programming language known for its simple and easy code structure. It allows programmers to write code in fewer lines than other programming languages. It provides vast built-in libraries and functions, making it the go-to language for rapid application development.

File handling is an essential topic in the programming world. It helps in data persistence, file manipulation, and data backup and recovery. Python provides different modes for opening files. In this Answer, we will look into some file opening modes in detail.

Syntax

my_file = open('file_name.txt' , 'mode')
Syntax to open file in python
  • open() is the main function that takes two parameters which are explained below:

    • file_name.txt is the name of the file that we need to open.

    • mode is the mode in which we need to open the file.

Modes for opening a file

Python provides different modes for opening files. Some of the important modes are explained below:

  • r: Opens the file in read mode and returns an error if the file does not exist.

  • w: Opens the file in write mode. If the file does not exist, then it creates a new one. Otherwise, it removes all text from the file and inserts the new text.

  • a: Opens the file in append mode. If the file does not exist, then it creates a new one. Otherwise, it adds the new text at the end.

  • x: Creates a file with the specified name. If the file already exists, it returns an error.

Examples

Now we will see examples to open files in some of the modes.

Open file in r mode

main.py
my_file.txt
# Code to open file in read mode
my_file = open('my_file.txt' , 'r')
print(my_file.read())
my_file.close()
Coding example to open file in read mode

The code explanation is given below:

  • Line 2: We open the file named my_file.txt in read mode r.

  • Line 3: We read the contents of the file using the read() command.

  • Line 4: We close the file after performing operations on it. It is important to close the file. Otherwise, it won't be accessible for further use.

Open file in w mode

main.py
my_file.txt
print("******Following is the text before opening the file in write mode: ")
my_file = open('my_file.txt') # Opening the file in read mode
print(my_file.read())
my_file.close()
print()
my_file = open('my_file.txt' , 'w') # Opening the file in write mode
my_file.write("Hello everyone! We successfully wrote in our file")
my_file.close()
print("****Following is the text after opening file in write mode:")
my_file = open('my_file.txt')
print(my_file.read())
my_file.close()
Coding example to open file in write mode

The code explanation is given below:

  • Line 10: We open the file named my_file.txt in write mode w.

  • Line 11: We write the text Hello everyone! We successfully wrote in our file in the file using the write() command and the previously written text gets removed.

Open file in a mode

main.py
my_file.txt
print("******Following is the text before opening the file in write mode: ")
my_file = open('my_file.txt')
print(my_file.read())
my_file.close()
print()
my_file = open('my_file.txt' , 'a') # Opening the file in append mode
my_file.write("\nHello everyone! We successfully appended the text in our file")
my_file.close()
print("****Following is the text after opening file in write mode:")
my_file = open('my_file.txt')
print(my_file.read())
my_file.close()
Coding example to open file in append mode

The code explanation is given below:

  • Line 10: We open the file named my_file.txt in append mode a.

  • Line 11: We append the text Hello everyone! We successfully appended the text in our file at the end of the file using the write() command.

Open file in x mode

my_file = open('my_file2.txt' , 'x') #Creating file using create mode
my_file.close()
my_file = open('my_file2.txt' , 'w')
my_file.write("The file my_file2.txt is created")
my_file.close()
my_file = open('my_file2.txt' , 'r')
print(my_file.read())
Coding example to create file

The code explanation is given below:

  • Line 1: We create the file named my_file2.txt using mode x.

  • Lines 4–9: To test that our file is created, we open my_file2.txt in write mode and write the text The file my_file2.txt is created. We then read the text of the file, which confirms that our file is created.

my_file = open('my_file2.txt' , 'x') #Creating file using create mode
my_file.close()
my_file = open('my_file2.txt' , 'x') #Creating file with the same name
my_file.close()
Code to explain that creating two files with the same name in x mode results in an error.

ERROR: If we try to create two files with the same name, then we see that the code in line 4 generates an error.

Conclusion

Python provides us with built-in modes to manipulate files. Three more modes, including b, t, and +, are also used to open files. b mode opens the file in binary mode for reading or writing. t mode opens the file in text mode for reading or writing (default mode). + mode opens the file for both reading and writing. Moreover, we can also use a combination of the modes mentioned above to open files, e.g., rb, w+, etc.

RELATED TAGS

python
python3
file handling
file reading

CONTRIBUTOR

Muhammad Huzaifa Khan
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?