File operations are fundamental for any program that needs to store or retrieve data persistently. This means that data can be saved to a storage device (like a hard drive or SSD) and retrieved later, even after the program has stopped running. Python provides built-in functions and modules to interact with files efficiently.
Core Concepts:
1. Opening Files (`open()` function):
To perform any operation on a file, you first need to open it. The `open()` function creates a file object, which is then used to interact with the file. It takes at least two arguments: the `filename` (path to the file) and the `mode`.
`file_object = open('filename.txt', 'mode')`
2. File Modes:
The `mode` argument specifies how the file will be used:
- `'r'` (Read): Default mode. Opens a file for reading. Raises `FileNotFoundError` if the file doesn't exist.
- `'w'` (Write): Opens a file for writing. Creates the file if it doesn't exist. If the file already exists, its content is truncated (emptied).
- `'a'` (Append): Opens a file for appending. Creates the file if it doesn't exist. Data is written to the end of the file without deleting existing content.
- `'x'` (Exclusive Creation): Creates a new file and opens it for writing. Raises `FileExistsError` if the file already exists.
- `'b'` (Binary): Used with other modes (e.g., `'rb'`, `'wb'`) for binary files (images, executables). Data is read/written as bytes.
- `'t'` (Text): Default mode (e.g., `'rt'`, `'wt'`). Used for text files. Data is read/written as strings, with encoding applied.
3. Reading Files:
Once a file is open in read mode, you can read its content using various methods:
- `file_object.read()`: Reads the entire content of the file as a single string.
- `file_object.readline()`: Reads one line at a time from the file.
- `file_object.readlines()`: Reads all lines from the file and returns them as a list of strings.
- Iterating over the file object: `for line in file_object:` reads line by line, which is memory-efficient for large files.
4. Writing Files:
When a file is open in write (`'w'`) or append (`'a'`) mode, you can write data to it:
- `file_object.write(string)`: Writes the given string to the file. It does -not- automatically add a newline character; you must include `\n` explicitly.
- `file_object.writelines(list_of_strings)`: Writes a list of strings to the file. Again, it does not add newlines.
5. Closing Files (`file_object.close()`):
After performing operations, it's crucial to close the file using `file_object.close()`. This releases the file handle, saves changes, and frees up system resources. Failing to close files can lead to data corruption or resource leaks.
6. The `with` Statement (Context Manager):
The preferred and most Pythonic way to handle files is using the `with` statement. It ensures that the file is automatically closed, even if errors occur, making your code safer and cleaner.
`with open('filename.txt', 'mode') as file_object:`
` perform file operations here`
The file is automatically closed when the `with` block is exited.
7. Error Handling: File operations can raise exceptions (e.g., `FileNotFoundError` if you try to read a non-existent file, `PermissionError` if you don't have the necessary rights). It's good practice to wrap file operations in `try-except` blocks.
Other Operations (using `os` module):
For more advanced file system operations like checking if a file exists, deleting, renaming, or listing directory contents, the `os` module provides powerful functions (e.g., `os.path.exists()`, `os.remove()`, `os.rename()`).
Example Code
!/usr/bin/env python3
import os
file_name = "my_document.txt"
print(f"--- Starting File Operations Example ---\n")
1. Writing to a file (mode 'w' - write, overwrites if exists)
print(f"1. Writing content to '{file_name}' (mode: 'w')...")
try:
with open(file_name, "w") as file:
file.write("Hello, Python world!\n")
file.write("This is the first line of content.\n")
file.write("And this is the second line.\n")
print(f" Successfully wrote initial content to '{file_name}'.")
except IOError as e:
print(f" Error writing to file: {e}")
2. Reading from the file (mode 'r' - read)
print(f"\n2. Reading all content from '{file_name}' (mode: 'r')...")
try:
with open(file_name, "r") as file:
content = file.read()
print(f" Content of '{file_name}':\n---\n{content}--- (End of file content)\n")
except FileNotFoundError:
print(f" Error: The file '{file_name}' was not found.")
except IOError as e:
print(f" Error reading file: {e}")
3. Appending to the file (mode 'a' - append)
print(f"\n3. Appending new content to '{file_name}' (mode: 'a')...")
try:
with open(file_name, "a") as file:
file.write("This line was added via append mode.\n")
file.write("Another line appended.\n")
print(f" Successfully appended content to '{file_name}'.")
except IOError as e:
print(f" Error appending to file: {e}")
4. Reading line by line from the file after appending
print(f"\n4. Reading content line by line from '{file_name}' after appending...")
try:
with open(file_name, "r") as file:
print(f" Content of '{file_name}' (line by line):")
for i, line in enumerate(file):
print(f" Line {i+1}: {line.strip()}") .strip() removes leading/trailing whitespace, including newline
except FileNotFoundError:
print(f" Error: The file '{file_name}' was not found.")
except IOError as e:
print(f" Error reading file: {e}")
5. Demonstrating file not found error
print(f"\n5. Attempting to read a non-existent file...")
non_existent_file = "no_such_file.txt"
try:
with open(non_existent_file, "r") as file:
print(file.read())
except FileNotFoundError:
print(f" Caught expected error: '{non_existent_file}' does not exist.")
except IOError as e:
print(f" An unexpected I/O error occurred: {e}")
6. Clean up: Delete the created file
print(f"\n6. Cleaning up: Deleting '{file_name}'...")
if os.path.exists(file_name):
os.remove(file_name)
print(f" '{file_name}' deleted successfully.")
else:
print(f" '{file_name}' already deleted or never created.")
print(f"\n--- File Operations Example Finished ---")








File Operations