File handling is an important part of any programming language. Python offers several functions for handling files, such
as opening, reading, creating, writing, closing, or deleting them. In this article, we will discuss file handling in
Python.
What is File Handling in Python Language?
File handling is the ability to work with files on a computer’s file system using Python programming language. It involves
various operations on the file, such as creating a file, reading, writing, appending and closing the file. Python
provides built-in functions and methods before those file operations efficiently.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
File Handling Functions
The most commonly used file-handling functions are open(), read() and write(). The following table describes some common
file-handling functions in the Python language.
Here is the table:
Functions
Descriptions
open()
Used to open a file
readable()
This function checks whether the file can be read or not
readline()
This function reads a single line from a file
read()
This read the whole content of the file
writable()
This function checks whether the file is writable or not
write()
This function writes a string to the file.
writelines()
This function used to write multiple string at at time
close()
This function is used to close the file from the program.
Opening a File in Python
There is the open() function in Python language for opening a file. The basic syntax of a file in
Python language.
Syntax
file_object = open(‘file_name’, ‘mode’)
The open() function takes two parameters.
File_name: This parameter includes the file extension with its current working. If the file
location is elsewhere, then provide the absolute or relative path.
Mode: This is an optional parameter that defines the file opening method. The following table
describes possible options that can be passed.
Mode parameter table options:
Mode
Description
‘r’
This option reads a file and returns an error. If the file does not exist
‘w’
Writes to a file and creates the file if it does not exist or overwrites an existing file.
‘x’
Exclusive creation that fails if the file already exists.
‘a’
This mode appends and creates the file. If a file does not exist or overwrites an existing
file.
‘b’
This mode is used for non-textual files such as images
To read a file in Python language, the file must first be opened in the read mode. Python language offers several
methods of reading. If you want a read-only first line, use readline(), and if you want to read all the lines, use
redlines (). If you want to read a few characters of the file. Use the read(size) method. This method read() is used to
read all the content at a time.
The following program demonstrates the reading of a file in Python:
Filename: file.txt
Hello Neeraj Kumar, How are you
Hello, Buddy, I am a software engineer
Program
# Open file in read mode
file = open("file.txt", "r")
# Read entire file content
content = file.readline()
print(content)
# Close the file
file.close()
Output
Hello Neeraj Kumar, How are you
Creating Files in Python
To create a new file, you have to pass ‘w’ in the second parameter in the open function in Python. The following program
demonstrates how to create a file in Python.
Progarm
# Open a file in write mode
with open(“file2.txt”, “w”) as file:
# Write some content into the file
file.write(“Hello, world!n“)
file.write(“This is a Python file created using Python.n“)
file.write(“Isn’t it cool?n“)
Writing to Existing Files in Python
We can use the append method, which means appending something to a file. The ‘a’ mode allows you to open a file and
append content to it.
The following program appends a new at the end of the file.
f = open("file2.txt", "a")
f.write("nNew Line")
f.close()
Output
Hello, world!
This is a Python file created using Python.
Isn't it cool?
New Line
Closing the Files in Python
It is a good practice to close a file after work is completed in your specific file. There is a close() function. That
can be used for closing a file
To close a file, run the close() method on the file object.
f.close()
The following program demonstrates the close method example:
Program
f = open("data", "r")
f.close()
Deleting Files in Python
Removing files in Python requires establishing communication with the operating system. There is an OS library that
has a remove() method that we can use to delete a file.
The following program demonstrates the deletion of files in Python language.
Program
import os
if os.path.exists(‘file.txt’):
os.remove(“file.txt”)
else:
print(“The file does not exist”)
Conclusion
In this article, we learned about file handling in the Python language. File handling is very essential for various data
manipulation tasks. Understanding file handling in Python is essential for various data manipulation tasks. By
understanding basic operations like creating, opening, reading, writing, appending, and closing files, developers can
efficiently manage external data sources, ensuring robustness and reliability.
FAQs
How to close the file in Python language?
There is a close method which is used to close the file in Python language.
How to open a file in Python language?
This can be done using the open() function. This function returns a file object and takes two parameters: one that accepts the file name and another that accepts the mode.
How do I read the contents of a file in Python?
You can read the contents of a file using methods like “read(),” “readline(),” or “readlines(),” depending on whether you need the entire file, a single line, or all lines.
How do I write a file in Python?
Writing to a file is accomplished using the ‘write()’ method. This method can be written in the file using the write mode ‘w’.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.