Python FunctionsPython Functions1

Python Exception HandlingPython Exception Handling1

Python File Operations – Read, Write, Update & Delete Files



In this lesson, you’ll learn how to work with files in Python — how to create, read, write, update, and delete files. This is often called CRUD operations: Create, Read, Update, Delete.

Why File Operations Matter

In real life, programs often need to store data — like saving notes, writing logs, or updating settings. Python makes it easy to work with files on your computer.

1. Creating and Writing to a File

This will create a file and write some text inside it.

file = open("example.txt", "w")
file.write("Hello from Python!")
file.close()    

Explanation:

What Happens?

A new file called example.txt is created with this content:

Hello from Python!

2. Reading from a File

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()    

Explanation:

Output:

Hello from Python!

3. Updating (Appending) a File

file = open("example.txt", "a")
file.write("\nAdding a second line.")
file.close()    

Explanation:

Output in the file:

Hello from Python!
Adding a second line.

4. Deleting a File

Python doesn’t delete files directly — but we can use a helper from the os module:

import os
os.remove("example.txt")    

Explanation:

After this:

The file is permanently deleted from your folder.

Best Practices for File Handling

1. Always close your files

Reason: Leaving files open can cause problems like data not being saved.

2. Use with open(...) instead of open() and close()

This is the safer and preferred way. Python closes the file for you automatically.

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

3. Always check if the file exists before deleting

import os
if os.path.exists("example.txt"):
    os.remove("example.txt")
else:
    print("File does not exist.")

Reason: Trying to delete a file that doesn’t exist will cause an error.

Conclusion

Now you know how to create, read, update, and delete files in Python — the basics of file handling! These simple steps are used in many real-world programs. Always follow best practices to avoid errors and keep your code clean.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M