Introduction to Python File Operations
Python is the extensively used web-based or website development programming language that facilitates any type of input to be incorporated in the codes. In python, files can be created, read, updated, deleted, and managed while considering. The types of files are taken differently, especially the binary files and text files. One can set the file functional modes like ‘r’ for read mode, ‘w’ for write mode, ‘x’ for returning an error if the file already exists, ‘t’ for text mode, and ‘b’ for binary mode. The most commonly used Python file operations are open(), close(), read(), writelines(), remove(), flush(), detach(), tell(), next(), etc.
Opening a Python File
The very first operation to work on a file is to open it. In Python, the open() function (built-in function) is used to open a file in both read and write mode. This function returns a file object. In the open() function, we define two arguments in which the 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”||It opens a file in reading mode|
|“w”||It 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+”||It opens a file in both reading and writing mode|
|“b”||Opens a file in binary mode (in case of images, .exe files)|
|“t”||It 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()
- 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 used in that file and 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 the finally block so that it will run every time, even in case of exceptions.
Example using try and finally
try : file = open (“abc.txt”,’w’) finally: file.close()
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 that 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 a 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. The writing method will overwrite the file’s content 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) file.close()
Deleting a File
To delete a file in Python, the remove() method is used. For this, one needs to import the os module to the program.
import os; os.remove (“abc.txt”)
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.|
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 one needs to perform and have good knowledge of all the file methods. Like for reading a file, there are several different methods available in Python used in different scenarios. So only with deep knowledge only can you 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 –