File Handling in Python

File Handling in Python

Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. This file handling concept in python is also easy and short. Python treats file differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.

 

As the part of programming requirement, we have to store our data permanently for future purpose. For this requirement we should go for files.

Files are very common permanent storage areas to store our data.

Types of Files:

There are 2 types of files

1) Text Files:  Usually we can use text files to store character data Eg: abc.txt

2) Binary Files: Usually we can use binary files to store binary data like images, video files, audio files etc…

Opening a File:

Before performing any operation (like read or write) on the file, first we have to open that file. For this we should use Python’s inbuilt function open()

But at the time of open, we have to specify mode, which represents the purpose of opening file.

f = open(filename, mode)

The allowed modes in Python are

1) r ->open an existing file for read operation. The file pointer is positioned at the beginning of the file. If the specified file does not exist then we will get FileNotFoundError. This is default mode.

2) w ->open an existing file for write operation. If the file already contains some data then it will be overridden. If the specified file is not already available then this mode will create that file.

3) a -> open an existing file for append operation. It won’t override existing data. If the specified file is not already available then this mode will create a new file.

4) r+ -> To read and write data into the file. The previous data in the file will not be deleted. The file pointer is placed at the beginning of the file.

5) w+ -> To write and read data. It will override existing data.

6) a+ -> To append and read data from the file.It wont override existing data.

7) x -> To open a file in exclusive creation mode for write operation. If the file already exists then we will get FileExistsError.

All the above modes are applicable for text files. If the above modes suffixed with ‘b’ then these represents for binary files. Eg: rb,wb,ab,r+b,w+b,a+b,xb

f = open(“abc.txt”,”w”)

We are opening abc.txt file for writing data.

 

Closing a File:

After completing our operations on the file, it is highly recommended to close the file.

For this we have to use close() function.

f.close()

 

Writing/Creating a File:

Another useful operation widely used, after opening a file, is writing into a file. Writing into a file in Python is easy but an attentive task. Writing into a file is typically done by opening the file in write ‘w’ or append ‘a’ mode. Writing into a file can be done using the .write() method to our file. Caution needed to be followed while using the ‘w’ write mode as it can erase existing content present in the file.

Example 1:

file = open(“myfile.txt”, “w”)

file.write(“Hello Alln”)

 

Example 2:

file = open(“myfile.txt”, “a”)

file.write(“I am using append moden”)

Writing Data to Text Files:

We can write character data to the text files by using the following 2 methods.

1) write(str)

2) writelines(list of lines)

f=open(“abcd.txt”,’w’)

list=[“sunny\n”,”bunny\n”,”vinny\n”,”chinny”]

f.writelines(list)

print(“List of lines written to the file successfully”)

f.close()

OUTPUT:

abcd.txt:

sunny

bunny

vinny

chinny

 

While writing data by using write() methods, compulsory we have to provide line seperator(\n), otherwise total data should be written to a single line.

Reading Character Data from Text Files:

We can read character data from text file by using the following read methods.

read() -> To read total data from the file

read(n) -> To read ‘n’ characters from the file

readline() -> To read only one line

readlines() -> To read all lines into a list

 

Eg 1: To read total data from the file

f=open(“abc.txt”,’r’)

data=f.read()

print(data)

f.close()

OUTPUT:

sunny

bunny

chinny

vinny

 

Closing a File in Python

At last, after opening and performing the reading, writing operations, it is important to close the file. This is done using .close() method. Let’s understand this with an example:

file = open(“myfile.txt”, ‘r’)

print(file.read())

file.close()

Related Posts:

Python Tutorial – Learn Python

What is Python? What makes Python so Powerful?

Variables in Python – Constant, Global & Static Variables

Namespacing and Scopes in Python

Operators in Python

Data Types in Python

STRING Data Type in Python

LIST Data Structure in PYTHON

TUPLE Data Structure in PYTHON

Differences between List and Tuple

SET Data Structure in PYTHON

DICTIONARY Data Structure in PYTHON

Database Programming in Python

What is Multithreading in Python?

Python Exception Handling Using try, except and finally statement

Python Random module

Python reduce() Function

Python map() Function

Python filter() Function

Lambda Function in PYTHON (Anonymous Function)

Python Interview Question And Answers