File Handling In Python

Python has a very unique feature for file handling. Unlike in other programming languages user does not require to import the library to perform operations on File handling.

Basically to work with files, we will be using modes in Python. Some of the modes we frequently use are

1.Write only – w
2Read only – r
3.Read and Write only – r+
4.Append – a

Based on the Mode we can perform opertions on files. Like if you give Write only(w) mode then, you will be able to write only and cannot read the data from the file.

Some of the inbuilt functions we need to know before working with files.

1.Open() : Open() method will open the files in our system. You need to give the filename to be opened.

Need to pass any one of the mode in which the file has to be opened. Like

filename = open(filename, “r”)

filename = open(filename, “w”)

filename = open(filename, “a”)

When we donot specify the mode in the method. By default python will take Read Mode.

2.Read() : Read method is used to read the data from the file. Reading the data from file can use any one of the methods

Method Name Explanation
read will read and returns single line
readline Will read line by line
readlines will read list of lines at a timePreviousNext

3.Write() : Write method will write data to file. Based on our requirement we can use any one of the method.
Method Name Explanation
Write() Will write a sequence of characters to a file
Writelines() will write a group of lines to a filePreviousNext

4.Append() : Append method appends the data to the file instead of overwriting the existing data.

5.Close() : When we have completed our tasks like reading or writing the data. We can close the file.

How to write data to a file using Python?

OUTPUT:

Python_Write_To_File_Example

DATA WRITTEN IN TEXT FILE AFTER EXECUTION :

Python_Writing_Data_To_File_Example

Line 1 : Here you are opening the “PythonFile.txt” file in write mode and writing some data into the text file.

Line 2 : Writing the data into file using write method

Line3 : Closing the “PythonFile.txt” file using close method.

How to read data to a file using Python?


OUTPUT:

Python_Read_File_Example

Line 1 : Here you are opening the “PythonFile.txt” file in read mode and writing some data into the text file.

Line 2 : Reading the data into file using write method

Line3 : Closing the “PythonFile.txt” file using close method.

How to append data to a file using Python?


OUTPUT:

Python_Append_Data_Example

Line 1 : Here we are opening the “PythonFile.txt” file in append mode.

Line 2 : Writing the data into file using write method, the data will be appended to the existing data.

Line3 : After giving line break, entering new line of text.

Line4 : Closing the “PythonFile.txt” file using close method.

Leave a Comment

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