File Handling in Python – Open, Read, Write, and Close

File Handling in Python – Open, Read, Write, and Close

3 mins read2K Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Nov 11, 2022 18:11 IST

File handling in Python is an important part of any web application. Python offers several functions for opening, reading, creating, writing, closing, or deleting files in python. In this article, we will briefly discuss how to handle files in Python.

2022_11_MicrosoftTeams-image-78-1.jpg

When you write any Python program, you save it in a file, and each file has its unique name and file extension. Files permanently store the data in non-volatile memory. Python allows users to handle the file, i.e., you can open, read, write, delete, or close files. This article will discuss different methods of file handling in Python.

To handle files in Python, you don’t need to import any external library or module; it can be performed using the built-in python function

Basics of file handling in Python:

  • Open a file 
  • Read/write/create/delete
  • Close a file 

The most used function in file handling is open().

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

File Handling in Python

Apart from the most commonly used file handling functions: open(), read(), write(), and close(), there are a lot more functions that are used for file handling in Python.
Here is a list of some commonly used file-handling functions in Python.

Function Description
open() Used to open a file.
readable() Used to check whether the file can be read or not.
readline() Used to read a single line from the file.
readlines() Used to read all the content in the form of lines.
read() Used to read whole content at a time.
writable() Used to check whether the file is writable or not.
write() Used to write a string to the file.
writelines() Used to write multiple strings at a time.
close() Used to close the file from the program.
Introduction to Python Range Function
Python Map() Function
Python Sorted() Function

How to open a file in Python

Python has a built-in function open() to open the file.

  • open () returns a file object that is called a handle.
    • It is used to read or modify the file.

Syntax


 
x = open (file_name, access_mode)
Copy code

Parameters

file_name: The name of the file that you want to open

access_mode: read, write, append

Mode Description
r Read Mode (default value)
w Write Mode (file is opened in write-only mode)
a Append Mode (Opens a file for appending at the end of the file without truncating)
x Create Mode (Creates a new file but will return an error if the file already exists.
t Open the file in text mode.
b Opens the file in binary mode.Binary mode returns bytes. It is mainly used while dealing with the non-text file such as images.
+ Opens the file for updating (reading and writing)

Example:


 
#open a file
o = open ('nl.txt') #it is a default mode, i.e. read only mode
o = open ('nl_txt', w) #it will open the file for writing
Copy code

Also Read: How to Read and Write Files Using Pandas 

Also Read: Exception Handling in Python

How to read a file in Python

To read a file in Python, the file must first be opened in the read mode.

  • Python offers several methods of reading.
    • If you want a read-only first line only, use readline (), and if you want to read all the lines in the form of lines, use readlines ()
    • If you want to read a few characters of the file, use read (size)
    • read () used to read all the content at a time.

Example:


 
#read a file
nl = open('nl.txt','r') # it will open the file in read mode
nl.readline() # it will read the first line of the file
nl.read(10) # it will read the first 10 charcter of the file
nl.read() # it will return the whole text
Copy code

How to Create a new file in Python

To create a new file, we have to open a file using one of the two parameters:

x: it will create a new empty text file iff there does not exist any file with the same name; otherwise, it will throw an error

w: it will create a file, whether any file exists with the same or not, i.e., it will not return an error if the same file name exists.

Example:


 
#create a file
nl = open ('nl.txt', 'x') # it will create a new empty file but will throw an error if the same file name exists
nl = open ('nl.txt', 'w') # it will create a file but if the same file name exist it will overwrite
Copy code

How to Write in an existing file in Python

Python offers two methods to write in an existing file:

  • write () method
    • It will add a single line at a time

Example:


 
# write into an existing file
with open('nl.txt','w') as nl:
nl.write('This is the first line\n')
nl.write('This is the second line\n')
nl.write('this is the third line')
Copy code
  • writelines () method
    • It allows to insert multiple string at a time

Example:


 
nl = open('nl.txt', w)
#it allows to write all the line in one go
nl.writelines('This is the first line\n', 'This is the second line\n', 'This is the third line')
nl.close()
Copy code

How to close a file in Python

Once you are done with all the operations, you need to close the file correctly.

  • The close () commands will terminate all the resources and will free the system
  •  It is a good practice to close the file.

Example


 
#close a file
nl = open('nl.txt', 'r')
print(nl.read())
nl.close()
Copy code

Conclusion

In this article, we have briefly discussed how to open, read, create, write, and close files in python.

Hope, you will like the article.

Keep Learning!!

Keep Sharing!!

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio