File Handling in Python

Python file handling operations are also known as Python I/O deal 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’:

Become a Professional Python Programmer with this complete Python Training in Singapore!

Now that we have got an idea of what text and binary files are, we are ready to dive into the discussion of different file handling methods and python file operations. Following is the list of all topics covered in this module:

So, without further delay, let’s get started.

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 , access_mode, buffer)

Here,

  • The file_name refers to the file which we want to open.
  • The access_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.

Some of the most common access modes are listed below:

Modes Description
r Opens a file only for reading
rb Opens a file only for reading but in a binary format
w Opens a file only for writing; overwrites the file if the file exists
wb Opens a file only for writing but in a binary format
a Opens a file for appending. It does not overwrite the file, just adds the data in the file, and if file is not created, then it creates a new file
ab Opens a file for appending in a binary format

Here’s an example of Python open function and Python readlines for reading files line by line. Say, this is how our text file, ‘demofile.txt’ looks like:

This is just a text file
But this is a newline

Now here’s a code snippet to open the file using file handing in Python.

f= open(‘demofile.txt’, ‘r’)
f.readline()

With the help of the open function of Python read text file, save it in a file object and read lines with the help of the readlines function. Remember that f.readline() reads a single line from the file object. Also, this function leaves a newline character (n) at the end of the string.

Output:

‘This is just a text file,n’

Go for this in-depth job-oriented Python Training in Hyderabad now!

Writing into a File

The write() method is used to write a string into a file.

Get 100% Hike!

Master Most in Demand Skills Now !

Syntax of the Python write function:

File_object.write(“string”)

Example:

i=open(“demotext.txt”,”w”)
i.write(“Hello Intellipaat”)

Here, we are opening the demotext.txt file into a file object called ‘i’. Now, we can use the write function in order to write something into the file.

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

The close() function is used to close a file.

Syntax of the Python close function:

File_object.close()

Example:

j=open(“intellipaat.txt”,”r”)
k=j.read()
print(k)
j.close()

Output:

Hello Intellipaat

We have the perfect professional Python Course in Bangalore for you!

Career Transition

Non-Tech to IT Associate | Career Transformation | AWS Certification Course - Intellipaat Reviews
Non Tech to DevOps Engineer Career Transition | Intellipaat Devops Training Reviews - Nitin
Upskilled & Got Job as Analyst After a Career Break |  Data Science Course Story - Shehzin Mulla
Successful Career Change after Completion of AWS Course - Krishnamohan | Intellipaat Review
Got Job Promotion After Completing Artificial Intelligence Course - Intellipaat Review | Gaurav
Intellipaat Reviews | Big Data Analytics Course | Career Transformation to Big Data | Gayathri

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")

Further, check out our offers for Python training Courses and also refer to the trending Python interview questions and answers prepared by the industry experts.

Methods of File Handling in Python

There are different file handling in Python which are as follows:

  1. rename(): This is used to rename a file.
import os
os.rename(existing file_name, new file_name)
  1. remove(): This method is used to delete a file in Python.
import os
os.remove(“abc.txt”)
  1. chdir(): This method is used to change the current directory.
import os
os.chdir(“new directory path”)
  1. mkdir(): This method is used to create a new directory.
import os
os.mkdir(“new directory path “)
  1. rmdir(): This method is used to remove a directory.
import os
os.rmdir(“new directory path”)
  1. 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

So, here’s the end of the Python file handling tutorial, where we answered the question, ‘What is file handling in Python?’ Here, we have also discussed different file handling in Python with examples that will be helpful while working on real-world projects.
With this, we come to the end of this module on Python Tutorial.

Now, let us go ahead and discuss how to make our program more robust and secure from potential failures. Now, if you want to know why Python is the most preferred language for data science, you can go through this on Python Data Science tutorial.

Course Schedule

Name Date Details
Python Course 30 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 06 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 13 Apr 2024(Sat-Sun) Weekend Batch
View Details