Python File Handling

 

File Handing: File handling in Python is the way to store data in a file. These stored data can be used later for performing various operations.

.Why we need File Handling: Till know we are writing programs in such a way that we are getting input from user and returning the output. We are not storing any value/output anywhere. But in real life applications, we make some applications which store the values and that values can be used later for various operation.

Example: We can take the example of login/registration system. When user do registration by filling their information. Their info. is stored in file or databases. And later when user logins by filling their login credentials, then it search for the details entered by user. If details exist in file or database then user successfully login.

How many types of Data Files in Python?

There are three types of files in python: 
1). Text files
2). Binary files
3). CSV files

(i). Text files: Text files are the files which store information in ASCII and Unicode characters. Each line of text in text file is terminated by EOL (End of Line) special character ie. full stop(.). We use .txt extension for saving text files. If we do not save our file by using .txt extension then by default extension is file.

(ii). Binary files: Binary files stores the information in binary format ie. 1 or 0. Our machine also uses binary languages to store information in our memory. There is no delimiter for a line. Translator are not require by machine to translate binary files as machine can understand binary format text.

Translators are required in case of text files as machine do not understand text format file. So translator translates text to binary format and hence file is stored into the machine memory. Binary files are more secure.

(iii) CSV files: CSV files are comma separated values file. It is a text file.

Difference between Text and Binary Files

Text Files

Binary Files

It stores information in ASCII and Unicode 

characters.

It stores information in the form 

of images, audio etc.

Text files are slower as compared to binary files.

Binary files are faster to read and 

write for programs.

It uses extension .txt.

It uses .dat extension.

Special character full stop (.) is used to terminate line.

There is no delimiter in Binary file.

Easy to understand by humans.

Difficult to understand by humans.

 File Access modes in Python

Mode

Function Descriptions

r

Opens file for reading and this is the Default Mode.

rb

Opens file for reading only in Binary format. Default Mode for Binary files.

r+

Opens file for both reading and writing purposes.

rb+

Opens file for both reading and writing purposes in Binary format.

w

Opens file for writing only. If file already exists, then it overwrites the file 

else new file will be created.

wb

Opens file for writing only in Binary format.

w+

Opens file for both reading and writing.

wb+

Opens file for both reading and writing in Binary format.

a

Opens file for appending, pointer at end of the file. If file does not exist, 

it creates a new file for writing.

ab

Opens file for appending in Binary format.

a+

Opens file for both appending and reading.

ab+

Opens file for both appending and reading in Binary format.

 

Open File in Python 

1). Open File: There are three types of files ie. text file, binary files and csv files. We will talk about text file. So, to perform any operation on input/output data and to store that data in file, we need to create a file first in which we can store that data.
Syntax 1:

FileObject=open(‘<filename>’, ‘mode’)

Two ways are shown above to open a file. We can use any of them. There is some difference between both syntax. In first one, inside square bracket only one parameter is required ie. file name/ file path.

Actually by default mode of opening file in read mode ie ‘r’ mode. If we do not pass any mode while opening file. Then it will open that file in read mode. In second, we have to just pass the file mode ie. ‘r’ etc.

Syntax 2:

f = open("test.txt") # To open a file

file.close() # To close a file

Note: Always remember the file name or file path you are giving should be the existing one. If file name or file path is wrong then it will return an error!

Example 1: Example of opening of text file.

f = open("test.txt")

if(f):

    print("File exist")

Output

#File exist

//It must create a text file first at the same location where your python file.

Important: This program is just for opening file. Other operations we will perform later.

2.) Create File: Above we learned, how to open existing file. Here we will learn how to create own file if file is not already existing.

There are two ways to create a file:
1). 
Using open() method
2). Using with open() statement

(i). open(): We mainly prefer to use open() method to create a file. We will use same function ie. open() that we have used for opening file. Only difference is instead of opening file in read mode we will open file in write mode.

Syntax

FileObject=open(‘<filename>’,’w’)

Here ‘w’ defines that the file we are going to open, should be open in write mode only. We open a file in write mode when we have to perform any operation on the data.

Example 1:

f = open("test.txt",w)

if(f):

    print("File exist")

Here our code successfully executed and you can see that our output and file created highlighted in yellow.

Note: If file name given inside open function is already exist. Then it will override the complete data in the existing file.

2). with open() statement: This is the very handy block method. Using this method, we can perform multiple operations in a single block. Operations we can perform like write, append, update, delete etc. The advantage of using with open statement() is that you don’t need to close file after performing any updation in file. Close() method is called automatically in with open() statement.

Syntax:

With open(<FileName>,<FileMode> as <File Handle>:

        f.write(“……”)

Note: Here f.write() is the operation (write operation on file). We will discuss about operations on file in next articles.

Example 1:

With open("abc.txt","w") as f:

    f.write("Hello Students How are you")