⬅ Previous TopicPython Lambda Functions
Next Topic ⮕Python Exceptions










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.
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:
open("example.txt", "w")
opens a file in write mode. If the file doesn’t exist, it will be created.file.write(...)
writes the text inside the file.file.close()
closes the file to save changes.
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:
"r"
means read mode.file.read()
reads all the content of the file.print(content)
shows the file content on screen.
Hello from Python!
3. Updating (Appending) a File
file = open("example.txt", "a")
file.write("\nAdding a second line.")
file.close()
Explanation:
"a"
stands for append mode — it adds text to the end without removing what’s already there.\n
is used to go to a new line.
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:
import os
loads the module to work with the operating system.os.remove(...)
deletes the file namedexample.txt
.
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.