File handling is essential for organizing, retrieving, and storing data. Using file handling in all of your programs is a mark of a good developer since it is a good programming practice. Python provides built-in file-handling methods to open, close, read, and write files. In this tutorial, we will learn how to perform all these operations on a text as well as a binary file in Python.
Opening A File
We must first open a file before we can read from or write to it. We can open the file by simply defining a function ‘open’ part of the python standard library. For using this function you don’t need to import any additional modules since it is available by default. Open function has two required parameters: ‘file name’ and ‘access mode’. In the first parameter we need to provide the name of the file we are opening and in the second parameter we need to provide the access mode which indicates how we want to open the file.
file = open("File_name","Access_mode")
What are Access Modes
There are seven types of access modes that can be used for operations on a file after opening it.
- Create(‘x’): Creates a file.
- Read Only(‘r’): Read an existing file. If a file doesn’t exist an error will be given. Default mode when opening a file.
- Write Only(‘w’): Write in an existing file. If the file doesn’t exist this mode will create a new file and write in it. When writing in an already written file this mode will overwrite the content and replace it with new content.
- Read and Write(‘r+’): Similar to the read mode while also permitting the writing to the file. This mode will read into the file first and then update by writing into it. If a file doesn’t already exist this mode will give an error. When writing in an already written file this mode will overwrite the content and replace it with new content.
- Write and read(‘w+’): Similar to Read and Write mode except the file will be written into first and then will be read. This mode will also overwrite and replace content if the file is already written in.
- Append only(‘a’): Write and update into an already existing file. If the file has already been written in this mode, it will not overwrite the existing content; instead, it will continue from where the previously written content ends
- Append and Read(‘a+’): Write into an already existing file and then read the file. Similar to the append-only mode it won’t overwrite in an already written file.
Methods to read and write in a file
Before we move onto reading and writing into a file we need to first learn what different read and write functions we will be using while performing the read and write operations. Following are different methods for reading data from files:
read(): Reads the entire content of the file as a string.
readline(): Reads one line of text from the file.
readlines(): Reads all lines of text into a list.
If you want to learn more about Python Programming, visit Python Tutorials.
Similarly writing methods are tools that allow you to save information, such as text and numbers, into a computer file. Following are different methods for writing data into a file:
write(): Writes a string to the file.
writelines(): Writes a list of strings to the file.
Finally we will combine both reading and writing functions and use four different methods for reading and writing in a file:
- Reading and Writing with Access Mode ‘r+’
- Reading and writing with access mode ‘w+’
- Reading and writing with access mode ‘a+’
- Reading and writing with access mode ‘r’, ‘w’, or ‘a’.
Before going towards the actual coding examples, keep in mind that if you are working on the text file, python takes the EOL (end of line) or in programming language “\n” as the terminating point for the line in the text file and store that in the file handler.
Note that the file to be read or written should be in the same directory in which your Python file is present. If not, then provide the complete path of that file. Otherwise, the code will give you the file error.
Reading and Writing with Access Mode ‘r+‘
Python provides access modes that allow us to handle and decide what should be done with the files once they are opened. The read and write access mode (‘r+’) is used for both reading and writing to files. The code below opens the file “myfile.txt” in read and write mode and reads all the lines in a text file.
f1 = open("myfile.txt", "r+") f1.readline()
In the above code, we have used a command file.readline() to read the specific line of the file. We can also specify the number of lines by passing an argument ‘n’ inside the file.readline(n) command.
file = open("myfile.txt", "r+") file.read()
Here, read() is used to just get the specific bytes in the form of a string of the given file. we can also write it as read(n).
To write into the file, we can use write() command as shown below. The text to be written is provided in the form of an argument inside the write() command.
We can also use writelines() function to write all the data once.
myline = "Welcome to entechin.com\nHope we learn something from here" f1.writelines(myline)
Reading and Writing with Access Mode “w+”
Another access mode that is used for both reading and writing is the ‘w+’ mode. It is almost similar to the ‘r+’ access mode.
f2 = open("myfile.txt", "w+")
In the above code, w+ is for reading and writing. If the file exists, then the previously stored data will be overwritten and the previous data will be deleted. This is the only difference between ‘r+’ and ‘w+’ modes. Once the file is opened using ‘w+’ mode, you can use the read(), readlines(), write() and, writelines() methods to read and write data.
Lines="First sample line\nNext line\nThird sample line" f2.writelines(lines) #difference between read and readlines print("Read result:\n ",f2.read(2)) print("\nReadlines result:\n",f2.readlines())
Read result: Fi Readlines result: First sample line Next line Third sample line
Reading and Writing with Access Mode “a+”
Access mode “a+” also reads and writes in a file. The only difference between writing using “a+” and writing using “r+” or “w+” is that while using “r+” or “w+” we will overwrite anything that is already written in a file while if we use “a+”, instead of overwriting we continue writing from the end after the existing data. We also need to add a seek function so that the cursor for the read function is set to the beginning.
file.seek(0) sets the file cursor to the beginning of the file (offset 0), allowing you to read the content from the start. This is important because after appending data to the file, the file cursor is at the end of the file due to the previous write operation.
Let’s take the same file f2 that we used for the “w+” mode.
# Open a file in 'a+' mode f2 = open("myfile.txt", "a+") # Display existing content print("Existing content in the file:\n",f1.readlines()) # Append new data to the file new_data = "\nThis is new data to be appended to the file." f2.write(new_data) # Move the file cursor to the beginning and read the updated content f2.seek(0) # Display updated content print("\nUpdated content in the file:\n",f2.readlines())
Existing content in the file: First sample line Next line Third sample line Updated content in the file: First sample line Next line Third sample line This is new data to be appended to the file.
Reading and Writing with Access Modes “r”,”w” or “a”
You can utilize access modes “w” or “a” to write data into a file, and subsequently employ the access mode “r” to read the modifications. It’s important to note that you will require two distinct
open() functions for this process to function correctly: one for writing into the file using access mode “w” or “a”, and another for reading the updated file content with access mode “r”.
# Open a file in 'w' mode f3 = open("myfile.txt", "w") # Write data to the file data = "Writing in a file" f3.write(data) # Second open function to read the file f3 = open("myfile.txt","r") # Display the content print("Content in the file:\n",f3.readlines())
Content in the file: Writing in a file
How to Open, Read, and Write in a Binary file
Reading and writing in a binary file is similar to reading and writing in a text file, with the only difference being the addition of a ‘b’ to the access mode.
file = open("myfile.bin", "rb")
In the example above we are trying to open and read the binary file ‘myfile.bin’. We define the access mode as ‘rb’ where ‘r’ represents that the file is being opened for reading and b represents that it is a binary file. Similarly we can do this with any access mode we want. Simply defining the access mode and adding ‘b’ to it to represent a binary file.
file = open("myfile.bin", "w+b")
Closing a file
Always remember to close the file once you are finished so that the resources associated with the file can be released. A file can be closed using a simple ‘close’ function attached with the file object that was created when the file was opened. It’s a good practice to close files when you’re done with them, especially if you’re writing to the file, to avoid data loss and potential issues.
We hope you found the information in this python tutorial valuable and that it helped you grasp the essential concept of opening a file for both reading and writing. Understanding these fundamental operations in file handling is crucial for any programmer. Thank you for your time and attention. Happy coding!