File Handling
Reading from and Writing to Files
File handling is an essential skill for any programmer. It allows your programs to persist data by reading from and writing to files on the computer's storage.
Opening and Closing Files
The open()
function is used to open a file. It takes at least two parameters: the filename and the mode. The recommended way to work with files is using the with
statement, which ensures the file is automatically closed when the block is exited, even if errors occur.
Common File Modes:
"r"
- Read (default): Opens a file for reading. Raises an error if the file does not exist."w"
- Write: Opens a file for writing. Creates the file if it does not exist, and overwrites all existing content if it does."a"
- Append: Opens a file for appending new content to the end. Creates the file if it does not exist."x"
- Create: Creates the specified file. Raises an error if the file already exists.- You can also add
"+"
to a mode (e.g.,"r+"
) to enable both reading and writing.
Reading Files
Once a file is open in read mode, you have several ways to read its content.
# Assume 'myfile.txt' exists and contains text. try: with open("myfile.txt", "r") as f: # Option 1: Read the entire file into one string # content = f.read() # print(content)
# Option 2: Iterate line by line (more memory efficient for large files) for line in f: print(line.strip()) # .strip() removes leading/trailing whitespace like the newline character
except FileNotFoundError: print("The file does not exist.")
Writing and Creating Files
Using "w"
or "a"
mode allows you to write to a file.
# This will create 'newfile.txt' or overwrite it if it exists with open("newfile.txt", "w") as f: f.write("Hello, World!\n") # \n is the newline character f.write("This is a new file.")
This will append to the end of the file
with open("newfile.txt", "a") as f: f.write("\nThis line was appended.")
Working with Paths and Deleting Files
The os
module provides functions for interacting with the operating system, like checking if a file exists or deleting it.
import os
file_to_delete = "file_to_delete.txt"
Create a dummy file to delete
with open(file_to_delete, "w") as f: f.write("I am temporary.")
Check if the file exists before trying to delete it
if os.path.exists(file_to_delete): os.remove(file_to_delete) print(f"'{file_to_delete}' has been deleted.") else: print("The file does not exist")