Python File Handling
File handling in Python involves reading from and writing to files on the disk. It allows you to interact with external files to store or retrieve data. Here’s an overview of file handling with code examples:
Reading from a File
Reading Entire File
python
# Opening a file in read mode ('r')
file_path = 'sample.txt'
with open(file_path, 'r') as file:
content = file.read()
print(content)
Reading Line by Line
python
# Opening a file in read mode ('r')
file_path = 'sample.txt'
with open(file_path, 'r') as file:
for line in file:
print(line.strip()) # strip() removes newline characters
Writing to a File
Writing to a File
python
# Opening a file in write mode ('w')
file_path = 'output.txt'
with open(file_path, 'w') as file:
file.write("Hello, world!\n")
file.write("This is a test file.\n")
Appending to a File
python
# Opening a file in append mode ('a')
file_path = 'output.txt'
with open(file_path, 'a') as file:
file.write("Appending additional content.\n")
File Handling with Error Handling
python
file_path = 'nonexistent_file.txt'
try:
with open(file_path, 'r') as file:
content = file.read()
print(content)
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
Using Context Managers (with
Statement)
Using the with
statement ensures that the file is properly closed after its suite finishes, even if an exception occurs.
Summary
File handling in Python involves opening files, reading from them, writing to them, and closing them. The open()
function is used to open a file in different modes ('r'
for reading, 'w'
for writing, 'a'
for appending). The with
statement is used to automatically close the file after the block of code completes execution.
When working with files, it’s important to handle exceptions such as FileNotFoundError
(when trying to open a non-existent file) and other potential errors that may occur during file operations. Always close files properly to avoid resource leaks.
Experiment with these examples by creating and manipulating text files in your Python environment to understand file handling concepts better.