Day12 MaterialPDF
Day12 MaterialPDF
File handling in Python allows you to read from and write to files on your system. It is a
core aspect of many applications, as it enables data persistence.
Opening a File
Python uses the built-in open() function to work with files. The syntax is:
open(file, mode)
Reading Files
3. content = file.read()
4. print(content)
12. print(part)
Writing to Files
4. Appending to a File
10. file.writelines(lines)
A context manager automatically handles opening and closing resources, like files,
ensuring there are no memory leaks or issues due to forgetting to close a file.
print(content)
• Advantages:
Without with:
try:
content = file.read()
print(content)
finally:
file.close()
With with, this is handled implicitly, making your code cleaner and less error-prone.
Examples
dest.write(line)
content = file.read()
words = content.split()
data = file.read()
Important Points
1. Error Handling
o Always use try-except blocks when working with file operations outside
with to handle errors gracefully.
try:
except FileNotFoundError:
finally:
if file:
file.close()
2. File Modes
Mode Description
3. Efficient Resource Management Always prefer the with statement for file
handling as it minimizes the risk of resource leaks.
2. Data Processing: Read and process CSV or text data for analytics.