File Handling In Python

Introduction

 
A file is some information or data which is stored (save) in the computer storage devices. File handling is one of the most important parts of any language. Python language supports two types of files. The first one is a text file that store data in the form of text and readable by humans and computers. The second one is binary file that store binary data and readable by computer only. In this article, I will describe some basic file I/O functions.
 
Open and Close File
 
Before performing any read or write operation first we required to open a file. Now I will explain the syntax of the file open method.
 
Syntax:
 
File_Object=open(file_name , [access_mode],[buffer_size],[encoding])
 
Parameters:
 
Name Description
file_name The file_name is a string parameter that contains the name of the file
access_mode Define the mode in which the file will be open. It is an optional parameter. The default mode is read.
buffer_size The optional buffering argument specifies the file’s desired buffer size.For file operation, python use the system’s default buffering unless we configure the buffer size. We can configure the buffer size in the following ways.
 
• 0 means no buffer
• 1 means linear buffer
• (-)ve buffer means system’s default buffer size
• (+)ve value greater than 1 defines the approximate size of the buffer
encoding Specify encoding Algorithm
 
Access Mode:
 
Python provides different modes to open a file. Some basic modes are the following:
 
Mode Description
r Open a file for reading only. This is the default mode.
w Open file for writing only. If the file exists then it will overwrite the file otherwise first create a file and after then open the file.
rb Open file for reading only in binary format.
wb Open file for writing only in binary format. If the file doesn’t exist it will first create a file and after then open the file
r+ Open file for both reading and writing.
w+ Open a file for both writing and reading. If the file exists then it will overwrite the file otherwise first create a file and after then open the file.
rb+ Open file for both reading and writing in binary format.
wb+ Open a file for both writing and reading in binary format. If the file exists then it will overwrite the file otherwise first create a file and after then open the file.
a Open file for appending. If the file already exists then the pointer will set at the end of the file otherwise a new file will create.
ab Open file for appending in binary format. If the file already exists then the pointer will set at the end of the file otherwise a new file will create.
a+ Open file for appending and reading. If the file already exists then the pointer will set at the end of the file otherwise a new file will create.
ab+ Open file for appending and reading in binary format. If the file already exists then the pointer will set at the end of the file otherwise a new file will create.
 
Example:
  1. File_Obj=open("News.txt","w");  
  2. print("File Name=",File_Obj.name);  
  3. print("File Open Mode=",File_Obj.mode);  
  4. print("File is Closed=",File_Obj.closed);  
  5. print("Encoding Algo is =",File_Obj.encoding);  
  6. File_Obj.close(); #Close The file  
  7. print("File is Closed=",File_Obj.closed)   
Output:
 
File Name= News.txt
File Open Mode= w
File is Closed= False
Encoding Algo is = cp1252
File is Closed= True
 
In the above example, we open a file in write mode and print the attribute of the file object. Here File_Obj.name describes the name of the file, File_Obj.mode describes the mode of opened file, File_Obj.closed returns that the file is closed or not, and File_Obj.encoding describes the encoding type used in the file. Python is using CP-1252 as the default encoding. CP-1252 is a common encoding on computers running Microsoft Windows.
 
Writing in a file
 
Python use write() method to write(insert) data into a file. The write() method can write string and binary data into the file.
 
Example:
  1. #Open File  
  2. File_Obj=open("News.txt","w");  
  3. #Write Data  
  4. File_Obj.write("My Name is Pankaj Kumar Choudhary \n");  
  5. File_Obj.write("I Live in Alwar Rajasthan \n");  
  6. File_Obj.write("I Love Programming \n");  
  7. File_Obj.write("I am doing my B.Tech. from Alwar");   
  8. #Close File  
  9. File_Obj.close();  
In above example we write some data into “News.txt” file. Let us check this file.
 
text file
 
We can see that data has been written in file successfully.
 
Reading a File
 
Python provides different ways to read the data from a file. We can read whole data or line by line data from a file. Now we take some methods to read the data.
 
read() Method
 
The read() method is used to read all data of a file at once.
  1. #Open File  
  2. File_Obj=open("News.txt","r");  
  3. #Read Data  
  4. Read_=File_Obj.read();  
  5. print(Read_);  
  6. #Close File  
  7. File_Obj.close();  
Output:
 
Reading a File
In read() method we can pass the number of bytes. If we pass n bytes as parameter, then read() method first reads the top n bytes from the beginning of file and after that next n bytes, until the end of file.
 
Let us take an example:
 
take an example
 
In the above example, we pass the number of bytes as a parameter in reading method.
 
readline() Method
 
As the name of readline() method indicate that this method is used to read data line by line from a file.
 
Example:
 
Let us take an example
 
We can send the number of bytes in readline() method to read the specific number of bytes from a file.
 
Example:
 
readline Method program
 
readlines() Method
 
The readlines() method read all lines of data from the file and return as a list.
 
Example 1:
 
readlines Method
 
Example 2:
 
readlines
 
Read File using Loop
 
We can use a loop to read the data from a file.
 
Example:
 
Read File using Loop
 
tell() Method
 
The tell() method is used to find out the current position of the pointer in the file.
 
Example:
 
 
seek() Method
 
The seek() method is used to change the position of the pointer in the currently open file.
 
Syntax:
 
File_Obj.seek(offset,[from])
 
Parameters:
 
offset: It defines the number of bytes to be moved.
 
from: It defines the reference position from where the bytes are to be moved.
  • 0 means beginning of the file
  • 1 means reference of the current line
  • 2 means the end of the file.
Example:
 
seek Method
 
remove() Method
 
The remove() method is used to remove(delete) any existing file. To remove any file just pass the name of that file into remove() method.
 
Syntax:
 
os.remove(File_Name)
 
Example:
 
remove Method
 
rename() Method
 
The rename() method is used to provide a new name to an existing file. The rename() method takes two parameters, first one is the name of the existing file and the second is the new name of the file.
 
Syntax:
 
os.rename(Old_Name,New_Name);
 
Example:
 
rename Method
 
fileno() Method
 
The fileno() method is used by the underlying implementation to request I/O operations from the operating system. This can be useful for other, lower level interfaces that use file descriptors, such as the fcntl module or os.read().
 
Example:
 
fileno Method
 
truncate() Method
 
The truncate() method truncates the file’s size. It means truncate() method resizes the stream to the given size in bytes. The current stream position isn’t changed. If the specified size of the file exceeds the current size, then the result is platform-dependent. This method would not work in case the file is opened in read-only mode
 
Example:
 
truncate Method
 
In the above example, we truncate all the files after 30 bytes. So now this file only contains 30 bytes of data.
 
Example:
 
Example
 
This example is the same as the previous example but in this example, we use “os.stat()” method to identify the size of the file.
 
writelines() Method
 
The writelines() method is used to write a list of lines to the stream. The list is used to writing multiple lines in the file.
 
Example:
 
writelines() Method
 
Example:
 
readable() return true if read operation is possible otherwise return false.
 
writable() return true if write operation is possible otherwise return false.
 
seekable() return true if the stream supports random access.
  1. File_Obj=open("NEWS.txt","r");  
  2. print("File is Readable=",File_Obj.readable());  
  3. print("File is Writable=",File_Obj.writable());  
  4. print("File is Seekable=",File_Obj.seekable());  
Output:
 
File is Readable= True
File is Writable= False

File is Seekable= True
 
Today we learned some basic file input and output methods. In the next article, I will explain OS Object Methods.
 
Thanks for reading this article.