Introduction to File Handling

File is collection of the data or information. In python we can access the file easily with the inbuilt function and is easy to manipulate in python. Generally in python, the files are divided into two, text file and binary file. Text file is normal one which consist of text and the binary is one which can be accessed by the computer alone.

There are Some Basic modes in which a file can be accessed,

“r” = It is used to open the file in the read form and so we cannot make any modification in the file. Initially if we open the file, it will be in read mode.

“w” = It is used to make some modification in the file.

“a” = It is used to append the data in the file.

Opening a file

To open a file in python, we use open() command. It has two arguement. First one is the name of the file in which we want to open and the second one is in which mode we want to open the file.

>>> a = open(” python.txt “)

>>> a

<_io.TextIOWrapper name=’python.txt’ mode=’r’ encoding=’UTF-8′>

Closing a file

To close a file in python, we use close() command.

a = open(” python.txt “)

>>> a

<_io.TextIOWrapper name=’love.txt’ mode=’r’ encoding=’UTF-8′>

>>> a.close()

Always make sure the you close the file explicitly after using the file. Do not open the file for no reason because it leads to corruption of data or even loss of memory.

Leave a comment