0% found this document useful (0 votes)
4 views10 pages

Day 20 Python File Handling

The document provides an overview of file handling in Python, including opening, reading, writing, and closing files. It explains different file modes such as read, write, and append, and highlights the importance of file handling for data analysts. Additionally, it includes code examples for reading and writing to files, as well as cleaning text data.

Uploaded by

patilsv654321
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Day 20 Python File Handling

The document provides an overview of file handling in Python, including opening, reading, writing, and closing files. It explains different file modes such as read, write, and append, and highlights the importance of file handling for data analysts. Additionally, it includes code examples for reading and writing to files, as well as cleaning text data.

Uploaded by

patilsv654321
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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")

You might also like