In this article, we will touch upon the file-handling capabilities of Python along with a few short scripts. File handling involves various operations including opening files, reading data from files, writing data to files and closing files. We will also see different types of modes to open a file and functions associated with a filehandle.
Why Open a File?
A file can be opened for the following purposes:
- To create a file
- To read data from a file
- To write data to a file
To Create a File
In order to create a file successfully, no matching file must already exist. If there is a matching file pre-existing, an error is returned as the file may not be created.
To Write Data to a File
The data can be written to a file in two ways:
- To overwrite the data in the file
- To append additional data to the file content
Modes of Data for Read and Write Operations
File read and file write have two modes available based upon the way the data is handled:
- Text mode
- Binary mode: Is important to retain platform specific encodings etc else file might get corrupted (if you open in txt more)
To open a file, open() function is used. The call to this function returns a file pointer, also called a file handler. The two arguments of open() function are filename and access mode. When the access mode is not specified, the access mode of “read in text mode” is implied. Once the file is open, the functions of this handler are invoked to create, read, edit or close the file. Consider the two examples of the usage of open() function and file handler listed below:
fh = open("filename") print (fh.read()) fh.close() #script 2 fh = open("filename","rt") print(fh.read()) fh.close()
Both of these example scripts perform the same set of operations. In the second argument “rt” of open() function:
“t”: text mode
To close a file handler after use is a good programming practice. Use close() function for this. Doing so closes the file properly (having saved it, if it was edited) and frees the system resources so used.
Text Mode Vs Binary Mode
As mentioned earlier, there are two data modes to read or edit a file:
“t”: Text Mode.
If we want to read individual characters or strings or even complete lines of character strings from a file, we use:
open("filename","rt") # OR open("filename") # r,w,x: r is default. t,b: t is the default.
If we want to write individual characters or strings or even complete lines of character strings to a file, we use:
open("filename","wt") # overwrite mode to overwrite the existing file data if any # OR open("filename","at") # append mode to add newer data to the existing file data if any
“b”: Binary Mode.
If we want to read files in binary encoded format (image files or executable binaries for example), we use:
If we want to modify the contents of files in binary mode, we use:
To Create a New File, To Read from a File, to Overwrite to a File and to Append to a File
“r”: to open a file in read mode; it returns an error if the file does not exist.
“w”: to open a file in overwrite mode; it creates the file if the file does not exist.
“a”: to open a file in append mode; it creates the file if the file does not exist.
“x”: to create a file; it returns an error if the file already exists.
Functions to Read Data from a File
There are three functions to read data from a file opened in “read” mode:
read(): When used without any arguments, it returns the whole data of the file. When used with a numeric argument, it returns the specified number of characters from the file.
readline(): It returns only one line of data from the file. When called the first time on a file, it returns the first line. When called further, it returns the next single line if any.
readlines(): It returns the list of all the lines read sequentially from the file.
The Function to Write Data to a File
write(): It writes its argument to the file. For example:
fh1 = open("filename1.txt", "w") # Notice "w" mode fh1.write("Only this data will persist in the file!") fh2 = open("filename2.txt", "a") # Notice "a" mode fh2.write("This data will be added to the end of the file!")
How To Delete a File?
In order to delete a file, “os” module of Python is required. So, we import the module and use its os.remove() function as follows:
import os os.remove("filename.txt")
How To Delete a Directory (Folder)?
In order to remove a directory, “os” module is required. So, we import the module and use its os.rmdir() function as follow:
import os os.rmdir("dirname")
A directory can be removed only if it is empty.