Introduction to Python File Operations
Python is simple, powerful and one of the widely used programming languages for web development. Being one of the powerful languages, it provides the facility of file handling to its users. It allows to create, read, write, update and delete a file. Unlike other programming languages, Python provides a very easy way to manage the files. Python treats binary and text files differently. Before performing any operations in a file, we need to open it first and then close after the operations are done in order to free the resources tied with it. In this topic, we are going to learn about Python File Operations.
Opening a Python File
The very first operation to work on file is to Open it. In Python, open() function (built-in function) is used to open a file in both read and write mode. This function returns a file object. In open() function we define two arguments in which first is the file name and the second is the mode in which we want to open that file.
file = open (“abc.txt”, “r”)
In the above example, the user wants to open a file named “abc.txt” in the read mode. Similarly, users can open a file in different modes like “w” for write mode and “a” for append mode. In Python, the user can also specify the binary or textual mode in which he wants to open a file. It is not mandatory for a user to specify the mode of the file if no mode is specified then by default Python will open a file in reading “r” mode.
file = open (“abc.txt”)
The above two ways of opening a file will perform the same action, i.e. open a Python file in read mode. Let’s understand different file modes in Python:
|“r”||Opens a file in reading mode|
|“w”||Opens a file in write mode|
|“a”||Opens a file in append mode (adding text at the end of the file)|
|“x”||Creates a specified file, returns an error if the file already exists|
|“r+”||Opens a file in both reading and writing mode|
|“b”||Opens a file in binary mode (in case of images, .exe files)|
|“t”||Opens a file in text mode|
- Read mode
file = open (“abc.txt”,’r’) for (x in file):
print x // prints the whole content of each line stored in x one by one
- Write mode
file = open(“new.txt”, ‘w’)
file.write (“hello I am learning file operations in Python”) // write the content in file file.close()
4.8 (3,969 ratings)
- Append mode
file = open (“test.txt”,’a’)
file.write (“hello this will append content in the file”) // append content at the end of file.close()
Closing a file
It is a good practice to close a file after the desired operations are done on it as this will free up all the resources which are used in that file and can be allocated somewhere else by the Operating System. For closing a file in Python, the close() method is used.
Although it is not mandatory to close a file as the Python uses the garbage collector to clean the unreferenced objects but it is a good practice and we must do it.
file = open (“abc.txt”,”a”) file.write (“append the text”) file.close()
It does not take any parameter like opening a file but this method is not totally safe as in case of exceptions it might exit the code without closing a file. For this, it is better to use the close() method in finally block so that it will run every time even in case of exceptions.
Example using try and finally
try : file = open
Reading a File
To read a file in Python, we need to open it first in the read mode. There are several methods of reading a file provided by Python. Let’s understand them one by one:
- read() method: This method reads the whole file at a time. This method returns \n for the new line. Once the whole file is completed we get a whole empty string so we need to set the cursor again using seek() and tell() methods.
This is line 1
This is line 2
file = open (“abc.txt”, ‘r’) print file.read() // This is line 1
// This is line 2
- readline() method: This method is used to read the file one line at a time till the \n character is found in the file. It adds \n at the end of the line.
file = open (“abc.txt” , ‘r’) print file.readline() // This is line 1
- readlines() method: This method is used to read the whole file but line by line. It updates the file by each line which is returned.
file = open (“abc.txt”, ’r’) print file.readlines() //This is line 1
// This is line 2
- read(n) method: This method is used if we want to read specified length of characters in a file.
File = open (“abc.txt”, ‘r’) print read(5) // ‘This ‘ (including 1 space after s) (read 5 characters of a file)
Writing a file
To write a file in Python we need to first open the file either in write “w”, append “a” or exclusion creation “x” mode.
There is a minor difference between append and write mode in Python and one needs to be very careful about this that append method adds the content at the end of the file, i.e. it will not affect the data if the file is already created and have some data in it. But the write method will overwrite the content of the file if the file having some data is already present. This method does not return anything.
file = open (“abc.txt”, ‘r+’) file.write
(“this is line 1\n”) file.write (“this is
line 2\n”) file.close()
writelines() method: writelines() method is also used to write a sequence of strings to a file.
file = open (“abc.txt”, ‘w’)
lines = [“this is line 1”, “this is line 2”] file.writelines(lines)
Deleting a File
To delete a file in Python, remove() method is used. For this one needs to import the os module to the program.
import os; os.remove
Other File Operation
There are various other methods that are used with file objects for different operations:
|flush()||Flush the internal buffer. It has no return value|
|detach()||Returns the separated raw stream from the buffer|
|readable()||Returns true if the file stream can be read|
|seek(offset, from)||Used to set the file object’s current position to offset bytes from the bytes given|
|tell()||Returns the file current position|
|seekable()||Returns true if the file stream allows random access|
|writable()||Returns true if the file allows being written into|
|fileno()||Returns the file number (file descriptor) used by Operating System for I/O operations|
|next()||Returns the next line of the file|
|truncate([size])||Truncates the file to the size (optional) specified.|
Conclusion – Python File Operations
Working on files is one of the important concepts in web development. Different methods in file serve specific purposes. Before using any method one must know exactly what actually he needs to perform and should have good knowledge of all the file methods in depth. Like for reading a file, there are several different methods available in Python used in different scenarios. So only with the deep knowledge only can choose the right method in the right scenario.
This is a guide to Python File Operations. Here we discuss how to perform any operation in the python file and then close after the operations are done. You may also look at the following article to learn more –