How to open files in Python
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')
open()is the main function that takes two parameters which are explained below:file_name.txtis the name of the file that we need to open.modeis 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
# Code to open file in read modemy_file = open('my_file.txt' , 'r')print(my_file.read())my_file.close()
The code explanation is given below:
Line 2: We open the file named
my_file.txtin read moder.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
print("******Following is the text before opening the file in write mode: ")my_file = open('my_file.txt') # Opening the file in read modeprint(my_file.read())my_file.close()print()my_file = open('my_file.txt' , 'w') # Opening the file in write modemy_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()
The code explanation is given below:
Line 10: We open the file named
my_file.txtin write modew.Line 11: We write the text
Hello everyone! We successfully wrote in our filein the file using thewrite()command and the previously written text gets removed.
Open file in a mode
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 modemy_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()
The code explanation is given below:
Line 10: We open the file named
my_file.txtin append modea.Line 11: We append the text
Hello everyone! We successfully appended the text in our fileat the end of the file using thewrite()command.
Open file in x mode
my_file = open('my_file2.txt' , 'x') #Creating file using create modemy_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())
The code explanation is given below:
Line 1: We create the file named
my_file2.txtusing modex.Lines 4–9: To test that our file is created, we open
my_file2.txtin write mode and write the textThe 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 modemy_file.close()my_file = open('my_file2.txt' , 'x') #Creating file with the same namemy_file.close()
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.
Free Resources