⬅ Previous Topic
Python FunctionsNext Topic ⮕
Python Exception Handling⬅ Previous Topic
Python FunctionsNext Topic ⮕
Python Exception HandlingIn 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.
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.
This will create a file and write some text inside it.
file = open("example.txt", "w")
file.write("Hello from Python!")
file.close()
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.A new file called example.txt
is created with this content:
Hello from Python!
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
"r"
means read mode.file.read()
reads all the content of the file.print(content)
shows the file content on screen.Hello from Python!
file = open("example.txt", "a")
file.write("\nAdding a second line.")
file.close()
"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.Hello from Python!
Adding a second line.
Python doesn’t delete files directly — but we can use a helper from the os
module:
import os
os.remove("example.txt")
import os
loads the module to work with the operating system.os.remove(...)
deletes the file named example.txt
.The file is permanently deleted from your folder.
Reason: Leaving files open can cause problems like data not being saved.
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)
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.
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.
⬅ Previous Topic
Python FunctionsNext Topic ⮕
Python Exception HandlingYou 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.