Day 11: File Handling in Python
Efficient Strategies for Working with Files
Table of contents
Today marks my eleventh day of learning Python, and I'm excited to share my insights on File Handling in Python. Python simplifies file manipulation with its built-in classes dedicated to file operations. Let's delve into my understanding of this essential aspect of Python programming.
Working with File
File handling methods in Python empower us to perform essential tasks such as reading from, creating, or writing to files. Oftentimes, we find ourselves needing to store output in a text file for various purposes.
Reading file
we can use open
methods to read or write files.
file = open('test.txt', 'r')
# printing file line by line
for line in file:
print(line)
file: Himanshu Chauhan's blog
second line third line
third line
printing the whole file:
file = open('test.txt', 'r')
# Printing the file
print(file.read())
file: Himanshu Chauhan's blog
second line third line
third line
Printing the read file with with
statement.
with open('test.txt', 'r') as file:
print("file: ", file)
Writing file:
For writing file and creating files we can use open
method.
file = open('custom.txt', 'w')
file.write("Hello bro\n")
file.write("Hello bro\n")
file.write("Hello bro\n")
file.write("Hello bro\n")
file.write("Hello bro\n")
Conclusion
In this journey of exploring File Handling in Python, we've learned the fundamental techniques for reading from and writing to files. Python's built-in classes provide powerful tools that simplify the process of file manipulation, allowing us to efficiently handle various file-related tasks.
When reading files, we utilize the open()
method with the appropriate mode, such as 'r' for reading. This enables us to access file contents line by line or read the entire file at once. Additionally, employing the with
statement ensures proper file handling and resource management.
For writing files, Python offers the flexibility to create and write to new files using the open()
method with the 'w' mode. With this capability, we can seamlessly generate output files and populate them with desired content.