Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

File Handling in Python – How to Create, Open, Append, Read, Write, & Close

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

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.

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
‘t’ Text mode. Use only for textual files by default
‘+’ Activates read and write methods.

 

Let’s open a file opening using the open() method

 

Filename: file.txt

 

Hello Neeraj Kumar, How are you

 

Program

 

file = open(“file.txt”,“r”) content = file.read() print(content) file.close()

  

Output

 

Hello Neeraj Kumar, How are you

Reading a File in Python

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

 

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

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
There is a close method which is used to close the 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.
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.
Writing to a file is accomplished using the ‘write()’ method. This method can be written in the file using the write mode ‘w’.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
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.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved