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 part of any language. Python language supports two types of files. First one is text file that store data in the form of text and readable by human and computer. 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 syntax of 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 contain name of file
access_mode Define the mode in which file will be open. It is optional parameter. Default mode is read.
buffer_size The optional buffering argument specifies the file’s desired buffer size.For file operation python use system’s default buffering unless we configure the buffer size. We can configure the buffer size in following ways.
• 0 means no buffer
• 1 means linear buffer
• (-)ve buffer means system’s default buffer size
• (+)ve value greater than 1 define approximate size of buffer
encoding Specify encoding Algorithm

Access Mode:

Python provide different modes to open a file. Some basic modes are the following:

Mode Description
r Open a file for reading only. This is default mode.
w Open file for writing only. If file exist then it will overwrite the file otherwise first create a file and after than open the file.
rb Open file for reading only in binary format.
wb Open file for writing only in binary format. If file doesn’t exist it will first create a file and after than open the file
r+ Open file for both reading and writing.
w+ Open a file for both writing and reading. If file exist then it will overwrite the file otherwise first create a file and after than 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 file exist then it will overwrite the file otherwise first create a file and after than open the file.
a Open file for appending . If file already exist then pointer will set at the end of file otherwise a new file will create.
ab Open file for appending in binary format . If file already exist then pointer will set at the end of file otherwise a new file will create.
a+ Open file for appending and reading. If file already exist then pointer will set at the end of file otherwise a new file will create.
ab+ Open file for appending and reading in binary format. If file already exist then pointer will set at the end of 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 above example we open a file in write mode and print the attribute of file object. Here File_Obj.name describe the name of file, File_Obj.mode describe the mode of opened file, File_Obj.closed returns that the file is closed or not, and File_Obj.encoding describe the encoding type used in 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 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 provide 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 above example we pass the number of bytes as parameter in read method.

readline() Method

As 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 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 file and return as a list.

Example 1:

readlines Method

Example 2:

readlines

Read File using Loop

We can use 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 pointer in file.

Example:



seek() Method

The seek() method is used to change the position of pointer in current open file.

Syntax:

File_Obj.seek(offset,[from])

Parameters:

offset: It define the number of bytes to be moved.
from: It define the reference position from where the bytes are to be moved.

 

  • 0 means beginning of file
  • 1 means reference of current line
  • 2 means 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 existing file. The rename() method takes two parameter, first one is name of existing file and second is new name of 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 truncate the file’s size. It means truncate() method resize the stream to the given size in bytes. The current stream position isn’t changed. If the specified size of the file exceed 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 above example we truncate all the files after 30 bytes. So now this file only contain 30 bytes of data.

Example:
`
Example

This example is same as previous example but in this example we use “os.stat()” method to identify the size of file.

writelines() Method

The writelines() method is used to write a list of lines to the stream. List is used to write multiple lines in 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 next article I will explain OS Object Methods.

Thanks for reading this article.