File Handling in Python

Files are used to save the data and information generated by the programs. After the complete execution of a program, the data is lost as you close the program. But you can create file objects which acts as an interface to the external files on your system. These files will hold your data permanently.

You can store data in two types of files:

  1. Text Files: These files hold textual data and saved as .txt files.
  2. Binary Files: These files store binary data i.e 0 and 1.

Operations on Python files

You can perform different operations on files like opening, closing, reading, editing etc. Python provides various built-in functions to do the same.

1. Opening a File in Python

Function used : open()
Syntax: file_object = open(file_name/location, processing_mode)

  • A built-in function open() creates a file object or a handle which has several methods like read(), write() etc.
  • This function opens the file which you provide as the argument. You may need to give the location where the file is stored on the computer.
  • Along with the file location, you need to specify that what you want to do with the file. It can be called as the processing mode. The function will present the data to you according to how you want to process it, whether you want to read or write or add something to the file.

In case, the file is not present, open() will create a new file with given name.

Processing modes to open a file are:

  • r, the read mode: This mode will let you read the data stored in a file. It is also the default processing mode.
  • w, the write mode: This mode will let you write into a file. But if something is already written in the file, it will be overwritten with write mode.
  • a, the append mode: This mode is similar to write mode as it also writes into a file. But, it doesn't disturb the existing data. It simply appends the new data to the file.
  • x, the exclusive mode: In this mode, the file is opened for exclusive creation.
  • t, the text mode: This mode returns the data in the form of text (string) when you read it. The files are opened in text mode only by default.
  • b, the binary mode: This mode is used with non-textual files. It returns the data in the binary form when read.

2. Closing a file in Python

Function used: close()
Syntax: file_object.close()

A file is opened to perform one or the other operation on it. So it is quite obvious that some of the resources will get engaged with those operations. If you keep on opening multiple files without closing any of them after the use, these files will go on occupying the resources. This will result into system crash and loss of data.

Thus to avoid such hard to recover situations, you must close every file after completion of the operations.

3. Reading a file in Python

Function used: read()
Processing mode: r
Syntax: file_object.read()

If you want to read an existing file, it must be opened in the r mode. Let us create a program to open an existing file named 'Tigers' which resides in the 'H Drive' within a folder named 'Sample Files', which looks like:

Example:

obj = open('h:\\Sample Files\\Tiger.txt','r') #opening the file in r mode
print(obj.read()) #reading the data and printing it as output
obj.close() #closing the file

Output:

Tiger is the largest Cat. 
It is the most dangerous and powerful animal. 
'Machli' is the World's Most Famous Tigress.

Explanation:

  • To open the file, file location as 'h:\\Sample Files\\Tiger.txt' and mode as 'r' are passed as parameters to the open() function. This function returns a file object named obj.
  • In the next step, the read() method reads the data from the given file and print() function displays it as the output.
  • In the end, the close() method closes the file and releases the resources used by the above operations.

This function also lets you read the file in multiple ways:

  • Line by Line: You can read the content of a file line by line with the help of the for loop.

    Example:
    obj = open('h:\\Sample Files\\Tiger.txt','r') #opening the file in r mode
    for line in obj:
        print(line)
    obj.close()​ #closing the file
    Output:
    Tiger is the largest Cat.
    
    It is the most dangerous and powerful animal.
    
    'Machli' is the World's Most Famous Tigress.​
  • Individual Line: readline() method is used to read a single line of the file. This method stops reading as it reaches the end of a line.

    Example:
    obj = open('h:\\Sample Files\\Tiger.txt','r') #opening the file in r mode
    print(obj.readline())
    obj.close() #closing the file​
    Output:
    Tiger is the largest Cat.​
  • Length: You can give the desired length as a parameter to the read() function, and it will only read the given length of the content.

    Example:
    obj = open('h:\\Sample Files\\Tiger.txt','r') #opening the file in r mode
    print(obj.read(5)) #5 is given as the length
    obj.close()  #closing the file​
    Output:
    Tiger​

4. Writing a file in Python

Function used: write()
Processing mode: w / a / x
Syntax: file_object.write(data)

The data you want to write into the file is given as the parameter to write() method. You must not forget to use quotation marks while entering a string into a file.

In order to write to a file, you can open it in one of three modes including w(write), a(append) and x(exclusive). As explained earlier, write mode always overwrites the data whereas append mode adds the data to the end of the file, so you may choose the mode wisely.

Opening the existing file in append mode:

obj = open('h:\\Sample Files\\Tiger.txt','a') #opening the file in a mode
obj.write('She died at the age of 20 years.') #adding the string to the data.
obj.close()  #closing the file

You can go to the file location and open your text file to see the result of the above operation as shown in the image below.

Opening the existing file in write mode:

obj = open('h:\\Sample Files\\Tiger.txt','w') #opening the file in w mode
obj.write('Save Tigers.') #writing into the file
obj.close()  #closing the file

As a result of the write mode, the data present in the file is overwritten.

You can also use the write() method to create a new file in the same way.

obj1 = open('h:\\Sample Files\\Status.txt','w')
obj1.write('Tiger is an endangered specie!!')
obj1.close()  #closing the file

This operation will create a new text file named 'Status' inside the folder 'Sample Files' in 'Drive H' and write the given string in the file.