File Handling in Python

File handling in Python, Python open Function, Python IO, Create a File in Python, Read a Text File, Write data to a file, and Delete a File.

Python IO – File Handling

Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files and Python treats files differently as text or binary.

open() function

We use open () function in Python to open a file in read or write mode. open () will return a file object, to return a file object we use open() function along with two arguments, that accept file name and the mode, whether to read or write.

In Python, a file operation takes place in the following order.

Open a file
Read or write (perform the operation)
Close the file

Syntax: open(filename, mode).

There are three kinds of mode, that Python provides and how files can be opened,

“r “, for reading.
“w”, for writing.
“a”, for appending.

“r+”, for both reading and writing

The mode argument is not mandatory. If not passed, then Python will assume it to be “r” by default.

File Handling Examples:

1. Read a File

The open() function returns a file object, which has a read() method for reading the content of the file:


f = open(“sample.txt”, “r”)

2. Read Only Parts of the File


Return the 5 first characters of the file:

f = open(“sample.txt”, “r”)

3. Read Lines

You can return one line by using the readline() method:


Read one line of the file:

f = open(“sample.txt”, “r”)

4. Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:

“a” – Append – will append to the end of the file

“w” – Write – will overwrite any existing content


Open the file “sample.txt” and append content to the file:

f = open(“sample.txt”, “a”)
f.write(“Now the file has more content!”)

#open and read the file after the appending:
f = open(“sample.txt”, “r”)

5. Overwrite the content

Open the file “sample3.txt” and overwrite the content:

f = open(“sample3.txt”, “w”)
f.write(“Woops! I have deleted the content!”)

#open and read the file after the appending:
f = open(“demofile3.txt”, “r”)

6. Create a New File

To create a new file in Python, use the open() method, with one of the following parameters

“x” – Create – will create a file, returns an error if the file exist


f = open(“myfile.txt”, “x”)

7. Delete a File

To delete a file, you must import the OS module, and run its os.remove() function:

#Remove the file “demofile.txt”:

import os

Python Step by Step Tutorial

Python Programming Videos

Follow me on social media:

1 thought on “File Handling in Python”

Comments are closed.