๐น 10. Using the "with" Statement โญ
The recommended way to work with files is by using the "with" statement.
It automatically closes the file after use.
with open("sample.txt", "r") as file:
print(file.read())You don't need to call
close()
manually.
๐น 11. Reading a File Line by Line
with open("sample.txt", "r") as file:
for line in file:
print(line.strip())This is useful for processing large files efficiently.
๐น 12. Real-World Data Science Example
Suppose you have a text file containing sales data:
100
250
175
300
Python code:
total = 0
with open("sales.txt", "r") as file:
for line in file:
total += int(line)
print(total)
Output:
825
In real-world projects, similar logic is used to process datasets before loading them into Pandas.
๐น 13. Common Mistakes
โ Forgetting to Close the File
file = open("sample.txt", "r")
print(file.read())Always use:
with open("sample.txt", "r") as file:
print(file.read())โ Opening a Non-Existent File
open("data.txt", "r")If the file doesn't exist, Python raises a
FileNotFoundError
.
Always verify that the file exists or handle exceptions appropriately.
๐ฏ Practice Questions
1. Create your own Python module with two functions and import it into another file.
2. Import the "math" module and calculate the square root of 144.
3. Create a text file and write five lines into it.
4. Read a text file line by line using the "with" statement.
5. Read a file containing numbers and calculate their average.
๐ฏ Key Takeaways
โ A module is a reusable Python file containing code.
โ A package is a collection of related modules.
โ Use "import" to access modules and their functions.
โ Use "open()" to read and write files.
โ Prefer the "with" statement because it automatically closes files.
โ File handling is a fundamental skill for reading datasets, logs, configuration files, and other real-world data sources.
Mastering modules, packages, and file handling will prepare you for working with Python libraries like Pandas, NumPy, and Scikit-learn, where data is frequently loaded from external files.
Double Tap โค๏ธ For More