• Articles
  • Tutorials
  • Interview Questions

File Handling in Python

Tutorial Playlist

File handling in Python is an essential skill that allows programmers to read from and write to files, thus enabling data persistence. This document outlines the key concepts and operations related to file handling in Python as discussed in the video.

Python file handling operations are also known as Python I/O. It deals with two types of files. They are:

  • Text files
  • Binary files

Even though the two file types may look the same on the surface, they encode data differently.

A text file is structured as a sequence of lines and, each line of the text file consists of a sequence of characters. Termination of each line in a text file is denoted with the end of line (EOL). There are a few special characters that are used as EOL, but comma {,} and newlines are the most common ones.

Image files such as .jpg, .png, .gif, etc., and documents such as .doc, .xls, .pdf, etc., all of them constitute binary files.

Watch this video on ‘Python File Handling’:

Video Thumbnail

Introduction to File Handling

File handling refers to the process of creating, reading, updating, and deleting files. In Python, file handling is made easy through built-in functions and methods. Files can be stored on disk or a network location, and Python provides a straightforward way to interact with them.

In this tutorial of File handing in Python, we will cover the following:

Creating a File

To create a new file in Python, you can use the open() method, along with one of the given parameters:

"x" - Create - will create a file, returns an error if the file exists
"w" - Write - will create a file if it doesn’t exist
"a" - Append - will create a file if it doesn’t exist
f = open("myfile.txt", "x")

Opening a File

To open a file, the built-in Python Function open() is used. It returns an object of the file which is used along with other functions.

Syntax of the Python open function:

obj=open(file_name , mode, buffer)
or 
obj=open(file_name , mode)

Here,

  • The file_name refers to the file which we want to open.
  • The mode specifies the mode in which the file has to be opened. It can be ‘r’, which is used for opening a file only to read it in Python, or ‘w’ used for opening a file only to write into it. Similarly, ‘a’ opens a file in Python in order to append, and so on. For more access modes, refer to the table given below.
  • The buffer represents whether buffering is performed or not. If the buffer value is 0, then no buffering is performed, and when the buffer value is 1, then line buffering is performed while accessing the file.

Different modes of File Opening

  • The mode parameter can take the following values:
  • ‘r’: Read mode – Opens the file for reading. The file must exist.
  • ‘w’: Write mode – Opens the file for writing, creating the file if it does not exist. If the file exists, it overwrites the file.
  • ‘a’: Append mode – Opens the file for appending. Data written to the file is added at the end without removing existing data.
  • ‘x’: Exclusive creation – Creates a new file and opens it for writing. If the file already exists, it raises an error.
  • ‘b’: Binary mode – Used for reading or writing binary files (e.g., images).
  • ‘t’: Text mode – This is the default mode. Text files are read and written in string format.

Get 100% Hike!

Master Most in Demand Skills Now!

Writing to a File

To write data to a file, you can use the following methods:

  • write(string): Writes the specified string to the file.
  • writelines(list): Writes a list of strings to the file.

Example of writing to a file:

with open(‘file.txt’, ‘w’) as file:

file.write("Hello, World!\n")

Reading from a File

The read() method is used to read data from a file.

Syntax of the Python read function:

File_object.read(data)
Example:
j=open(“intellipaat.txt”,”r”)
k=j.read()
print(k)

Output:

Hello Intellipaat

Closing a File

It is essential to close a file after its operations are complete to free up system resources. This can be done using the close() method. However, using the with statement automatically handles closing the file.

Example:

file = open('file.txt', 'r')
# Perform file operations
file.close() # Close the file

Deleting a File

To delete a file in Python, you have to import the module OS, and use the os.remove() function.

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

Checking if a File Exists

When trying to delete a file, it is a good idea to check if the file exists or not, to avoid getting an error.

import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")

Exception Handling in File Operations

When dealing with file operations, it is crucial to handle exceptions to avoid runtime errors. This
can be done using try and except blocks.

Example:

try:
with open('file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")

Others Methods of File Handling in Python

There are multiple other file handling methods available in Python which are as follows:

a. rename(): This is used to rename a file.

import os
os.rename(existing file_name, new file_name)

b. remove(): This method is used to delete a file in Python.

import os
os.remove(“abc.txt”)

c. chdir(): This method is used to change the current directory.

import os
os.chdir(“new directory path”)

d. mkdir(): This method is used to create a new directory.

import os
os.mkdir(“new directory path “)

e. rmdir(): This method is used to remove a directory.

import os
os.rmdir(“new directory path”)

f. getcwd(): This method is used to show the current working directory.

import os
print(os.getcwd())

Become a Python Expert

Other Methods of File Handling in Python

Following are the other common methods of file handling in Python, along with their descriptions

 

Method Description
close() To close an open file. It has no effect if the file is already closed
flush() To flush the write buffer of the file stream
read(n) To read at most n characters from a file. Remember that it reads till end of file if it is negative or none
readline(n=-1) To read and return one line from a file. Remember that it reads at most n bytes, if specified
readlines(n=-1) To read and return a list of lines from a file. Remember that it reads at most n bytes/characters if specified
seek(offset,from=SEEK_SET) It changes the file position to offset bytes, in reference to  (start, current, or end)
tell() It returns the current file location
writable() It returns true if the file stream can be written to
write(s) To write string s into a file and return the number of characters written
writelines(lines) To write a list of lines into a file

File handling in Python is a powerful feature that enables developers to manage data effectively. By understanding the various modes of file operations, as well as how to read, write, and delete files, you can create robust applications that interact with file systems efficiently. This tutorial has covered the fundamental concepts of file handling, but there are many more advanced techniques and libraries available in Python for specific use cases. Always remember to handle exceptions appropriately to ensure smooth execution of your file operations.

With this, we come to the end of this module on Python Tutorial.

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.