Day - 20
File Handling
in Python
A.I. Powered 30 Days Python Micro Course By Satish Dhawale ( Microsoft Certified Trainer )
• Layman Explanation
• File handling means:
• Opening a file
• Reading data from a file
• Writing data into a file
• Closing a file
What is File • Just like you open a notebook, write
something, read something, and then close it.
Handling?
• Technical Explanation
• File handling in Python uses the built-in
function:
open(filename, mode)
Modes:
Mode Meaning
"r" read
"w" write (overwrite)
"a" append (add new content)
"r+" read + write
"w+" write + read
Why File Handling is Important for Data Analysts?
1 2 3 4 5 6 7
Read log files Read data from Clean unwanted Store cleaned Save output for Create summary Automate
text reports characters results automated reports repetitive file
dashboards tasks
Opening & Reading a Text File
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
Read Line by Line
file = open("[Link]", "r")
for line in file:
print([Link]())
[Link]()
Read First N Characters
file = open("[Link]", "r")
print([Link](20))
[Link]()
Writing to a File
Write New Content (Overwrites file)
file = open("[Link]", "w")
[Link]("Python File Handling\n")
[Link]("This is Day 20 lesson.")
[Link]()
Append Content (Add to existing file)
file = open("[Link]", "a")
[Link]("\nAdding new line using append mode.")
[Link]()
Clean a Text File (Remove Spaces)
cleaned = []
with open("[Link]", "r") as f:
for line in f:
[Link]([Link]().title())
with open("cleaned_output.txt", "w") as f:
for city in cleaned:
[Link](city + "\n")