Python File Handling

A file handling mechanism is used to store the output of a program inside a file and to perform various operations (write, read, and delete) on it.
Python supports the file handling concept that allows us to read, write, and delete a file. We can also perform some additional options related to file handling concept.

File handling is an important part of any web application. Python has several functions for creating, reading, updating, and deleting files.


Opening a File

The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file


1. r – Read – Opens a file for reading(error if the file does not exist).
2. a – Append – Opens a file for appending( creates the file if it does not exist).
3. w – Write – Opens a file for writing (creates the file if it does not exist).
4. x – Create – Creates the specified file (returns an error if the file exists).

We can specify if the file should be handled as binary or text mode


1. t– Text – Text mode
2. b– Binary – Binary mode (e.g. images)

Example of the opening a file in all different mode

f = open("demofile.txt", "rt")  # here we opened the file for reading in the text mode
f = open("demofile.txt", "w")  # here we opened the file for writing 
f = open("demofile.txt", "wt")  # here we opened the file for writing in the text mode

Note: Make sure the file exists, or else you will get an error.


Reading a File

The key function to read the data from the existing file using the read() function. When we trying to read data from the file should be open in the read (r) mode.

Example of reading data from the file

f = open("demofile.txt", "r")
print(f.read())
Tutorials Class - Output Window

Hello Python

Here, we opened a file in the read mode. And read() function will read the whole data of the file.


Reading the whole data of the file through for loop

We can also read the whole data of the file with the help of for loop.

Example of reading whole data from the file

f = open("demofile.txt", "r")
for x in f:
  print(x)
Tutorials Class - Output Window

Hello Python


Reading particular data form the file

We can also specify a particular part of the file, which we are going to read.
By specifying the number of characters in the read function, we can read a particular number of characters.

Example of reading first 5 characters from the file

f = open("demofile.txt", "r")
print(f.read(5))
Tutorials Class - Output Window

Hello

Here we will be able to read only 5 characters.


Reading lines from the file

By the help of readline() function, we can read the first line of the file.

Example of reading first line from the file

f = open("demofile.txt", "r")
print(f.readline())
Tutorials Class - Output Window

Learning File Handling Concept in Python

Example to read first two line form the files

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Tutorials Class - Output Window

Learning File Handling Concept in Python.
File handling operations are reading, writing, updating and deleting a file.


Closing a file

With the help of the close() function, we can close the file in Python.

Example of closing a file

f = open("demofile.txt", "r") 
print(f.readline()) 
f.close()
Tutorials Class - Output Window

Learning File Handling Concept in Python.

Note: You should always close your files, in some cases, due to buffering, changes made to a file may not show until you close the file.


Writing in a file in Python

With the help of the function, we can write in a file in Python. The file should be opened in the write (w) mode.

Example of writing data to the file in write mode

f = open("demofile.txt", "w")
f.write("File handling is an important part of any web application.")
f.close()

Example of writing data to the file in append mode

This content will override the previous file content. If we don’t want to override the content of the file. We must open the file in the append mode.

f = open("demofile.txt", "a")
f.write("This is content which will be write in the file")
f.close()

Deleting a file in Python

For deleting a file we must import the os module, then with the help of the remove function, we can delete a file in Python.

Example of deleting a file

import os
os.remove("demofile.txt")

Delete Folder

To delete an entire folder, use the os.rmdir() method.

Example of deleting the entire folder

import os
os.rmdir("myfolder")


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.