Python - File Management

File Management in Python

 
Python programming language supports file management using File object which provides different methods to perform operations like open, read, write and append text into the files.
 
In this article, we will see the following methods and try to understand the file management concept in detail
 

Open()

 
This method is used to open the file. This method accepts two parameters, i.e., path or address of the file and access mode (read, write or append) open (file_address, access_mode). Access mode can be any of the following,
  • r: open a file with the read access mode
  • r+: open a file with the read and write access mode
  • w: open a file with write access mode
  • w+: open a file with write and read access mode
  • a: open a file with append access mode
  • a+: open a file with append and read access mode
Please note that ‘access_mode’ is an optional parameter and, by default, it is set to ‘read’. Let’s have a look at the example given below wherein you open a file that contains two lines of data and iterate through each line and print as an output to the console window.
  1. with open("c:\welcome.txt"as file: # Use file to refer to the file object  
  2.         for data in file: # this statement reads each line but one at a time  
  3.             print(data)  
Python - File Management
 
Open method raises an error ‘FileNotFoundError’ if the given file does not exist, as shown in the below example.
  1. try:  
  2.     with open("c:\welcomeNotExists.txt") as file: # Use file to refer to the file object  
  3.         #data = file.read()  
  4.         for data in file:  
  5.             print(data)  
  6. except FileNotFoundError as fileNotFoundError:  
  7.     print(fileNotFoundError)  
Python - File Management
 

read([size])

 
This method is used to read and return the file data as a string. This method accepts one parameter (optional) i.e., size (characters) of the data to be read. Let’s have a look at the example given below
 
Example 1
 
Open a file and read the entire data, i.e., two lines of data and print to the console window.
  1. with open("c:\\welcome.txt") as file:   
  2.         data = file.read()  
  3.  print(data)  
Python - File Management
 
Example 2
 
Open a file and read first six characters data and print to the console window.
  1. with open("c:\\welcome.txt") as file:   
  2.         data = file.read(6)  
  3.  print(data)  
Python - File Management
 

readline[size]

 
This method is used to read the first line and return as a string. This method accepts one parameter (optional), i.e., size (characters) of the data to be read. Let’s have a look at the example given below
 
Example 1
 
Open a file and read the first line whereas file contains two lines of data
  1. with open("c:\\welcome.txt") as file:   
  2.         data = file.readline()  
  3.  print(data)  
Python - File Management 
  
Example 2
 
Open a file and read the first six characters of the first line whereas file contains two lines of data 
  1. with open("c:\\welcome.txt") as file:   
  2.         data = file.readline(6)  
  3.  print(data)  
Python - File Management
 

readlines[size]

 
This method is used to read the entire data line by line and return as a list. This method accepts one parameter (optional) i.e., size (number of bytes) to be read. Let’s have a look at the example given below,
 
Example
 
Open a file and read the entire data line by line and return a list. You can pass an index to print any chosen line from the list output or the entire data to the console output 
  1. with open("c:\\welcome.txt") as file:  
  2.         data = file.readlines()  
  3.         print(data)   
 Python - File Management
 

write()

 
This method is used to write the data into the file. Either flush or close the file after writing data otherwise it will not save and reflect the changes. In the below example, we have read the data before and after writing the data for better understanding of the write operation, 
  1. def readData():  
  2.      with open("c:\\welcome.txt") as file:   
  3.         data = file.readlines()   
  4.         print(data)   
  5. try:  
  6.     print('read data before writing')  
  7.     readData()  
  8.     with open("c:\\welcome.txt"'a+') as file:   
  9.         file.write('written via python program')  
  10.         file.flush()    
  11.     print('read data after writing')   
  12.     readData()         
  13. except FileNotFoundError as fileNotFoundError:  
  14.     print(fileNotFoundError)  
  15. except Exception as ex:  
  16. print(ex)     
 Python - File Management
 

writelines()

 
This method is used to write multiple lines in a sequence. Let’s have a look at the below example to understand the method in a better way, 
  1. def readData():  
  2.      with open("c:\\welcome.txt") as file: # Use file to refer to the file object  
  3.         data = file.readlines()   
  4.         return data  
  5. try:  
  6.     print('read data before writing')  
  7.     data = readData()  
  8.     print(data)  
  9.     with open("c:\\welcome.txt"'a+') as file: # Use file to refer to the file object        
  10.         file.write('\n')        
  11.         file.writelines(data)  
  12.         file.flush()    
  13.     print('read data after writing')   
  14.     data = readData()  
  15.     print(data)         
  16. except FileNotFoundError as fileNotFoundError:  
  17.     print(fileNotFoundError)  
  18. except Exception as ex:  
  19.     print(ex)     
Python - File Management
 

next()

 
This method is used to iterate through the file data ( line by line) when a file is used as an iterator. This method returns the next input line. Let’s have a look the code implementation
  1. try:  
  2.     with open("c:\\welcome.txt") as file:  
  3.          try:   
  4.              line = next(file)  
  5.              while line:   
  6.                  print(line)   
  7.                  line=next(file)            
  8.          except Exception as e:  
  9.               print(e)   
  10.               file.close()  
  11. except FileNotFoundError as fileNotFoundError:  
  12.     print(fileNotFoundError)  
  13. except Exception as ex:  
  14.     print(ex)  
 Python - File Management
 

flush()

 
This method is used to flush the internal buffer. It has no return value. close() automatically flushes the data but if you want to flush the data before closing the file then you can use this method.
 

close()

 
Used to close an open file. A closed file cannot be read or written any more.
 

Conclusion

 
In this article we have read about various operations Python program provides for the text file management.


Recommended Free Ebook
Similar Articles