Example HTML page

File handling in Python

In this section i would like to provide only basic information regarding files on opening, writing, reading and closing files.

Introduction to File handling in Python

In this section I would like to depict the usage of actual data files. For this python is providing some basic functions and methods which are required for manipulating the files by default. This can be mostly done by using file object.

An open ( ) function

If you want to read/write a file first you have to open it by using a python’s built-in function known as open( ) function. It helps in creating a file object. With this object it is easy to call other supportive methods associated with it.

The below is the syntax of open( ):

file object = open(file_name [, access_mode][, buffering])

Here,

file_name         – It specifies the name of the file which you want to access.

access_mode  – It determines some of the modes like open, read, write, append and so on. This is an optional parameter and it considers ‘read’ mode by default.

buffering        0 represents no buffering, 1 represents buffering while file accessing.

Different modes of opening a file:

The following is the list of the different modes of opening a file.

Modes

Description

r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+ Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Ex

Here I am creating a text file with name as “vmsfile.txt” with “w+” mode. If already exists you can directly open that file.

>>> f=open(“vmsfile.txt”,”w+”)

>>> f

<_io.TextIOWrapper name=’vmsfile.txt’ mode=’w+’ encoding=’cp1252′>

Note

If you want to make sure that your file is created or not, you can just check in the folder where you save your python programs. There you will be displayed a file you created.

Attributes of file object

The following are the list of attributes which are related to a file object.

file.closed – It returns true if file is closed, false otherwise.

file.mode – It returns access mode with which file was opened.

file.name – It returns name of the file.

Ex

The below is a sample python program that performs all the above operations.

f=open(“thefile.txt”,”wb”)

print(“Created file is : “,f.name)

print(“Opening mode is: “,f.mode)

print(“Is the file closed? : “,f.closed)

Output

Created file is :  thefile.txt

Opening mode is:  wb

Is the file closed? :  False

Reading and writing files

The file object provides two methods namely write ( ) and read ( ) methods to write and read files.

The write( ) method:(Writing a text into a file)

After the creation of file we can put some data in that file. The write ( ) method is used to do this.

Performing write operation on the file we created.

>>> f=open(“vmsfile.txt”,”w”)                                      #write mode

>>> f.write(“A sample file chosen for testing file operations like\nopen\nwrite\nread\nclose”)

75

The read( ) method: (Reading text of that file)

If you want to read the content in that file use read( ) method.

>>> f=open(“vmsfile.txt”,”r”)                                         #read mode

>>> f.read( )

‘A sample file chosen for testing file operations like\nopen\nwrite\nread\nclose’

File positions

Here the offset value denotes the number of bytes to be moved. Initially the reference position starts from the offset value. If the offset value assigns to zero then beginning of the file is used as the reference position and if it is set to 1 then the current position is considered as the reference position.

Ex

>>> f=open(“vmsfile.txt”,”r”)

>>> f.read(10)

‘A sample f’

>>> f.read(16)

‘ile chosen for t’

>>> f.read(21)

‘esting file operation’

>>> f.read(4)

‘s li’

>>> f.read(7)

‘ke\nopen’

>>> f.read(26)

‘\nwrite\nread\nclose’

>>> f.read(3)

The close( ) method

This method closes the file and after that we can’t write anything unless it is opened.

>>> f.closed                                         #Returns false if it is not closed

False

>>> f.close( )

>>> f.closed                                         #Returns true after the file is closed.

True

We can also rename and delete the files we created. For this, Python os module is used. In next section you can refer os module.

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest