-
Classes
-
File operations
-
Comprehensions
-
loops
-
Python Installation
-
Numbers
-
Data Types in Python
-
Operators
-
Sequence Data types part 3 – Tuples
-
Sequence Data types part 2 – Lists
-
Expressions and statements
-
Data Unpacking
-
Functions
-
Dictionaries
-
Sequence Data types part 1-strings
-
if…else
-
Taking Input from the user
-
Python Typecasting
File operations
When dealing with data in daily scenarios, we may often need to store the data. But data stored in variables are temporary and get reset once we close our program. So, we may want to store the data in files. Let us learn to read/write data onto files in this section.
Writing to a file
To write, first we need a file. Create a file in the directory where you are having your python file. Let’s say we have a 1.py file. In the same directory as the file, create another file users.txt.
Now we have to write some data into this users.txt from the 1.py file.
Let us create a function writeToFile which when called should write some string into the users.txt file. In Python, we have a method called open which helps us to open a file in order to read or write data onto files. We can implement the open method as follows:
Here, we are passing two arguments to the open method. The first one is the path of the file on which we want to perform some action. The second argument is the mode of operation. Here, ‘w’ means write mode. The open method here is only opening the file for writing. But it does not perform any write operation on the file. To write data onto the file, we need to use the write method as follows:
Here, we are using the write method to write the text “Charles Babbage” onto the users.txt file. Finally, we are calling the writeToFile function to execute the code. After this code is executed, if we observe the users.txt file, we can see that the string “Charles Babbage” is written onto the file. But remember that in the beginning, we opened the file for writing. Therefore, it is also necessary to close the file after the writing operation is complete. It is unsafe to keep the file open after the desired operations are done. For that, we need to use the close method as follows:
This is how we open a file, write data onto it and safely close it.
Now, let us modify the code to write another piece of text onto the users.txt file as follows:
After running this code, we will observe that the previous text, “Charles Babbage” is replaced by the new text, “Charles Darwin”. But if we want to add(not replace) a new piece of text to the users.txt file, this approach won’t help us. For that, we just need to change the mode of operation. Till now, we were using the ‘w’ mode, which is write mode. But now we need to go with the append(‘a’) mode to add or append new text to the existing text in the file.
Let us modify our code as follows:
We have just replaced ‘w’ with ‘a’ and passed a new string(“Hello“) to the write method. Please keep in mind that the users.txt file had the text “Charles Darwin“ because of the previous code execution(write method with ‘w‘ mode). So, now when we run the above code with ‘a‘(append) mode, the text “Hello” will be appended to the “Charles Darwin“ text as follows in the users.txt file: Charles DarwinHello
This is totally correct as we told Python to append the new text to the old text. If we want all text in the file to be added in a new line, we need to add a new line character(\n) to the text that we are passing. To do this, first edit the users.txt file to remove all the text from it. Then run the following code:
Now, this will append the new text and move to a new line. If we repeat this code again, we get the following text in the users.txt file:
Hello
Hello
Please note that, we are opening the file using the open method, writing the desired text and then safely closing the file using the close method. For every operation, we need to repeat this opening and closing of the file. But Python has a better alternative for this. In Python, there is a with statement which can handle the opening and closing of files on its own. Let us see it in action.
Here, we are using the with statement to open the file in append mode(‘a‘). As you can see here, we are not writing separate open and close methods. The with statement opens the file for writing in append mode. Once the write operation is done, it automatically closes the file. This is syntactically less compared to the previous approach.
Reading a file
Let us now see how to read a file in Python. Please note that to write onto a file, we opened the file in write(‘w‘) mode. If we don’t specify the mode, the open method opens the file in read(‘r‘) mode by default. After opening the file in read mode, we need to use the read method to read the contents of the file.
Output:
Hello
Hello
Welcome
Here, the read method reads the whole file and returns the whole content of the file as a string. In the above code, we are not passing any argument to the read method. But we can also pass a size argument as below:
Output:
Hel
Here, the argument 3 tells Python up to how many bytes should be read. Here, it reads 3 bytes from the file as shown in the output. Here, it is to be noted that Python has read only up to 3 bytes and it will stay in that position until the file is closed. If we read the file again without closing the file, Python will continue reading from the same position where it left.
Let us consider the following code:
Output:
Hel
lo
Here, Python first reads the file up to 3 bytes and prints the characters. Hence, we get “Hel“ in the output. Then we read 2 bytes again before closing the file. Python starts reading from the last position of the file object. Hence, we get “lo“ in the output. But once we close the file using the close method, the file object’s position is reset and will read the file from the beginning if opened again.
If we want to know the file object’s current position, we can use the tell()method of the file object as follows:
Output:
Hel
3
Here, we can see that after reading 3 bytes, the tell() method is returning us the current position of the file object. If we want to move or change the position of the file object, we can use the seek() method as follows:
Output:
Hel
3
1
This way, we can change the file object’s position and start reading from there as well:
Output:
llo
Let us now see how to read a file using the with statement. Remember that we had a users.txt file. We will open the file and read it as follows:
Output:
Hello
Hello
Welcome
Here, we are using the read method which returns a string containing the contents of the specified file.