Python Programming – Operations on Files
Initially, we need to open the file first for reading or writing data into it. After performing operations on the file or saving data into it, it needs to be closed. It is necessary to close the file in order to release the resources acquired by the program. Hence, in Python, a file operation takes place in the following order.
- Open a file
- Read or write (perform the operation)
- Close the file
Opening a File
In Python, a file can be opened by the open() function. It is a very simple built-in function of Python to open a file. This function creates a file object, which would be utilized to call other support methods associated with it. The general syntax of the open method is given as follows:
|file object= open(file_name,access_mode, buffering)|
The open( ) function contains three parameters, which are elaborated as under:
• file_name: The filename argument is a string value that contains the name of the file that the programmer wishes to access.
• access_mode: The access_mode determines the mode in which the file has to be opened, i.e., read, write, append, etc. The detail of modes is given in the next section.
• buffering: If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line buffering is performed while accessing a file. If the programmer specifies the buffering value as an integer greater than 1, then buffering action is performed with
the indicated buffer size. The negative value of buffer size represents the system default behavior.
Apart from the above, the open() function can be used in two ways. In a first way, the programmer just needs to specify the FileName with an optional extension with a period (.). By just specifying the file name in the open() method as an argument, it creates the file in the current directory. Another way is to specify the complete path, where the programmer wants to save the file. The output of this function is assigned to a file object, which is used to read, write, or modify the file. The example for opening a file is given in Code 9.1. This method is directly applied to the Python prompt.
Code: 9.1. Illustration of opening a file using Python open()
|>>>fp = open(“data.txt”) # open file in current directory
>>>fb= open(“C:/Pythonprogs/data.txt”) # specifying full path
Alike, C, C++, and Java, a file can be opened in various modes depending upon the purpose. For that, the programmer needs to specify the mode whether read ‘r’, write ‘w’, or append ‘a’ mode. Apart from that, two other modes exist, which specify to open the file in text mode or binary mode. The default is reading in text mode. The text-mode returns strings while reading from the file. On the other hand, the binary mode returns bytes and this is the mode to be used when dealing with non-text files like images or executable files. The text and binary modes are used in conjunction with the r, w, and modes. The list of all the modes used in Python is listed in Table 9.1.
|R||Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.|
|Rb||Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file.|
|r+||Opens a file for both reading and writing. The file pointer placed at the beginning of the file.|
|rb+||Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.|
|W||Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.|
|Wb||Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.|
|w+||Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.|
|wb+||Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.|
|A||Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.|
|Ab||Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.|
|a+||Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.|
|‘x’||Opens a file for exclusive creation. If the file already exists, the operation fails.|
|‘a’||Opens for appending at the end of the file without truncating it. Creates a new file if it does not exist.|
|‘t’||Opens in text mode, (default)|
|‘b’||Opens in binary mode.|
|Opens a file for updating (reading and writing)|
The example code for opening a file in particular mode is given in Code:92.
Code: 9.2. Illustration of opening a file in a particular mode.
|fp = open(“data.txt”) # equivalent to V or ‘rt’
fp = open(“data.txt”,W) # write in text mode
fp = open(“img.jpg”,’r+b’) # read and write in binary mode
File Object Attributes
After opening a file, the programmer can access information about the file using various available attributes. The list of attributes is given in Table 9.2. with the description of each, the use of attributes is explained in Code 9.3.
|fp.closed||Returns true if the file is closed, false otherwise.|
|fp.mode||Returns access mode with which file was opened.|
|fp.name||Returns the name of the file.|
|fp.softspace||Returns false if space explicitly required with print, true otherwise.|
Code: 9.3. Illustration of file attributes.
|# This program creates a file and prints its attributes
# Open a file
Name of the file: data.txt
In Python version 3.x and above the encoding of files is made clear. Here., with encoding we mean either text mode or binary mode. Unlike other languages C and C++, the character ‘a’ does not imply the number 97 until it is encoded using ASCII(or other equivalent encodings). Hence, when working with files in text mode, it is recommended to specify the encoding type. Files are stored in bytes
Chapter 9: File Management in Python on the disk, we need to decode them into str (text) when we read into Python.
Similarly, encoding is performed while writing texts to the file. The default encoding depends on the platform whether Windows or Linux. The encoding scheme for Windows is ‘cpl252’ and ‘utf-8’ is used in Linux. Hence, one must not rely on the default encoding otherwise, the code can behave absurdly on different platforms. Thus, this is the preferred way to open a file for reading in text mode as shown in Code 9.4.
Code: 9.4. Illustration of file encoding.
|fp= open(“test.txt”,mode = ‘r’,encoding = ‘cpl252’) # for Windows
fp= open(“test.txt”,mode -= ‘r’,encoding = ‘utf-8’) # for Linux
Closing a File
In Python, the file can be closed by using the close() function. It is a built-in function provided by Python for manually closing a file and releasing all the resources acquired by it. Python automatically closes a file, when the reference object of the file is assigned to another file. However, it is a good programming practice to close the file using the close() function. The general syntax of the close() function is given as follows:
The programming example of closing a file is given in Code 9.5.
Code: 9.5. Illustration of closing a file.
|# This program creates and closes a file after printing its attributes
# Open a file
Name of the file: data.txt
This method is not entirely safe. If an exception occurs when we are performing some operation on the file, the code exits without closing the file. A safer way is to use a try…finally block as shown in Code 9.6.
Code: 9.6. Illustration of closing a file using try… finally (exception landling).
fp = open(“data.txt”,encoding = ‘utf-8’)
# perform file operations finally:
This way, we are guaranteed that the file is properly closed even if an exception is raised, causing the program flow to stop.