Python File Operation (With Examples) (2024)

A file is a named location used for storing data. For example, main.py is a file that is always used to store Python code.

Python provides various functions to perform different file operations, a process known as File Handling.

Opening Files in Python

In Python, we need to open a file first to perform any operations on it—we use the open() function to do so. Let's look at an example:

Suppose we have a file named file1.txt.

Python File Operation (With Examples) (1)

To open this file, we can use the open() function.

file1 = open("file1.txt")

Here, we have created a file object named file1. Now, we can use this object to work with files.

More on File Opening

Different File Opening Modes

Python allows us to open files in different modes (read, write, append, etc.), based on which we can perform different file operations. For example,

file1 = open("file1.txt")

Here, we are opening the file in the read mode (we can only read the content, not modify it).

Note: By default, Python files are open in read mode. Hence, the code open("file1.txt", "r") is equivalent to open("file1.txt").

Different Modes to Open a File in Python

ModeDescription
rOpen a file in reading mode (default)
wOpen a file in writing mode
xOpen a file for exclusive creation
aOpen a file in appending mode (adds content at the end of the file)
tOpen a file in text mode (default)
bOpen a file in binary mode
+Open a file in both read and write mode

Here are a few examples of opening a file in different modes,

# open a file in default mode (read and text)file1 = open("test.txt") # equivalent to open("test.txt", "rt")# open a file in write and text mode file1 = open("test.txt",'w') # open a file in read, write and binary modefile1 = open("img.bmp",'+b') 

Opening a File Using its Full Path

We can also open a file using its full path.

file_path = "/home/user/documents/file1.txt"file1 = open(file_path)

In this example, /home/user/documents/file1.txt is a full path to a file named file1.txt located in the /home/user/documents/ directory.

Note: To learn more about directories, please visit Python Directory.

Reading Files in Python

After we open a file, we use the read() method to read its content. For example,

Suppose we have a file named file1.txt.

Python File Operation (With Examples) (2)

Now, let's read the content of the file.

# open a file in read modefile1 = open("file1.txt")# read the file contentread_content = file1.read()print(read_content)

Output

This is a test file.Hello from the test file.

In the above example, the code file1.read() reads the content of the file and stores it in the read_content variable.

Note: If you need clarification about how the code file1.read() works, please visit Working of Python Objects.

Writing to Files in Python

To write to a Python file, we need to open it in write mode using the w parameter.

Suppose we have a file named file2.txt. Let's write to this file.

# open the file2.txt in write modefile2 = open('file2.txt', 'w')# write contents to the file2.txt filefile2.write('Programming is Fun.\n')file2.write('Programiz for beginners\n')

When we run the above code, we will see the specified content inside the file.

Python File Operation (With Examples) (3)

Be Careful While Writing to a File

If we try to perform the write operation to a file that already has some content, the new content will replace the existing ones. For example,

Suppose we have a file named file2.txt.

Python File Operation (With Examples) (4)

Now let's write to this file.

# open the file2.txt in write modefile2 = open('file2.txt', 'w')# write new contents to the file2.txt filefile2.write('Learning Python is interesting.\n')file2.write('File operations are useful.\n')

When we run the above code, the new content will replace any existing content in file2.txt.

Python File Operation (With Examples) (5)

Note: If we try to open a file that doesn't exist, a new file is created, and the write() method will add the content to the file.

Closing Files in Python

When we are done performing operations on the file, we need to close the file properly. We use the close() function to close a file in Python. For example,

# open a filefile1 = open("file1.txt", "r")# read the fileread_content = file1.read()print(read_content)# close the filefile1.close()

Output

This is a test file.Hello from the test file.

Note: Closing a file will free up the resources that are tied to the file. Hence, it is a good programming practice to always close the file.

Opening a Python File Using with...open

In Python, there is a better way to open a file using with...open. For example,

with open("file1.txt", "r") as file1: read_content = file1.read() print(read_content)

Output

This is a test file.Hello from the test file.

Here, with...open automatically closes the file, so we don't have to use the close() function.

Note: Since we don't have to worry about closing the file, make a habit of using the with...open syntax.

More on Python File Operations

Exception Handling in Files

If an exception occurs while working with a file, the code exists without closing the file. Hence, it's a good practice to use the try...finally block.

Let's see an example.

try: file1 = open("file1.txt", "r") read_content = file1.read() print(read_content)finally: # close the file file1.close()

Output

This is a test file.Hello from the test file.

Here, the finally block is always executed, so we have kept the close() function inside it. This ensures that the file will always be closed.

To learn more about exceptions, visit Python Exception Handling.

Note: Make a habit of using the with...open syntax while working with files so you don't have to worry about closing the file.

Some Commonly Used File Methods

There are various methods available with a file object. Some of them have been used in the above examples.

Here is the complete list of methods in text mode with a brief description:

MethodDescription
close()Closes an opened file
read(n)Reads the file content
seek(offset,from=SEEK_SET)Changes the file position to offset bytes, in reference to from (start, current, end)
tell()Returns an integer that represents the current position of the file's object
write(s)Writes a string to the file
writelines(lines)Writes a list of lines to the file
Python File Operation (With Examples) (2024)
Top Articles
Physical Therapist's Guide to Lumbar Radiculopathy and Sciatica
What is EVM Wallet - A Comprehensive Guide | Shardeum
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Frankie Dare

Last Updated:

Views: 5942

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Frankie Dare

Birthday: 2000-01-27

Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

Phone: +3769542039359

Job: Sales Manager

Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.