File handling in Python means working with files stored on your computer. It allows us to create, read, write, update, and delete files directly from code. This is useful for saving data permanently instead of keeping it only in memory.
Opening a File
Before you can do anything with a file—whether it’s reading it or writing to it—you must first “open” it using Python’s built-in open() function. This function acts like a key; it takes the name of the file and the “mode” (what you want to do with it) and gives you a file object to work with. Common modes include 'r' for reading, 'w' for writing, and 'a' for appending.
# We are opening a file named 'diary.txt' in 'read' mode # If the file doesn't exist, Python will show an error in 'r' mode file_object=open("diary.txt", "r")
Reading from a File
Once a file is open in read mode ('r'), you can pull information out of it into your program. Python provides methods like read() to grab the entire content at once, or readline() to read it line-by-line. This is similar to reading a book from the first page to the last; the computer reads the text exactly as it is stored.
# Assuming 'diary.txt' contains: "Today was a good day." file=open("diary.txt", "r") content=file.read() print(content) # Output: Today was a good day. file.close() # Always close the file to free up resources!
Writing to a File
Writing allows you to put new information into a file using the 'w' mode. However, you must be careful: opening an existing file in 'w' mode is like erasing a whiteboard before writing on it; it completely wipes out old content and replaces it with the new data. If the file doesn’t exist yet, Python will create a brand new one for you automatically.
# This will create 'notes.txt' (or overwrite it if it exists) file=open("notes.txt", "w") file.write("Remember to buy milk.") file.close() # The file now contains only: "Remember to buy milk."
Appending to a File
If you want to add information to a file without deleting what is already there, you use the append mode ('a'). This mode places your “cursor” at the very end of the file’s existing content. It is perfect for things like log files or adding new entries to a list, effectively letting you continue writing where you left off.
# We add a new line to our existing 'notes.txt' file=open("notes.txt", "a") file.write("\nAlso, buy eggs.") file.close()
# The file now reads: # "Remember to buy milk. # Also, buy eggs."
Deleting a File
Python does not have a simple keyword to delete files directly; instead, you must interact with the operating system using the os module. Deleting a file is permanent and cannot be easily undone, so it is good practice to check if the file actually exists before trying to remove it to avoid errors in your program.
importos
# Check if the file exists before deleting to prevent errors ifos.path.exists("notes.txt"): os.remove("notes.txt") print("File deleted successfully.") else: print("The file does not exist.")
Power User Feature: Pickling and Unpickling
Sometimes you need to save complex Python objects (like lists or dictionaries) rather than just plain text. Pickling converts these objects into a stream of bytes (0s and 1s) that can be saved to a file, essentially “freezing” the object. Unpickling is the reverse process, loading those bytes back into a working Python object.
importpickle
# Pickling: Saving a list to a binary file grocery_list= ["Apples", "Bananas", "Cherries"] file=open("list_data.pkl", "wb") # 'wb' means write binary pickle.dump(grocery_list, file) file.close()
# Unpickling: Loading the list back file=open("list_data.pkl", "rb") # 'rb' means read binary loaded_list=pickle.load(file) print(loaded_list) # Output: ['Apples', 'Bananas', 'Cherries']
Important Note on Best Practices
While the examples above use file.close(), modern Python developers prefer using the with statement. It automatically closes the file for you, even if an error occurs while the file is open.
withopen("diary.txt", "r") asfile: content=file.read() # No need to type file.close(), it happens automatically here!