0% found this document useful (0 votes)
2 views3 pages

4 Python Files Modules

The document covers file handling in Python, including reading and writing files, working with CSV and JSON formats, and exception handling. It also introduces the concept of modules and packages for code organization, along with common standard-library modules. Lastly, it briefly mentions setting up virtual environments and provides practice exercises for applying the concepts learned.

Uploaded by

dola.mbstu
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)
2 views3 pages

4 Python Files Modules

The document covers file handling in Python, including reading and writing files, working with CSV and JSON formats, and exception handling. It also introduces the concept of modules and packages for code organization, along with common standard-library modules. Lastly, it briefly mentions setting up virtual environments and provides practice exercises for applying the concepts learned.

Uploaded by

dola.mbstu
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

Part 4

File Handling & Modules


Files, CSV/JSON, Exceptions & Modules
1. Reading & Writing Files
with open("[Link]", "w") as f:
[Link]("Hello, Python!\n")
[Link]("File handling is easy.\n")

with open("[Link]", "r") as f:


content = [Link]()
print(content)

The with statement automatically closes the file, even if an error occurs.

2. Reading Line by Line


with open("[Link]", "r") as f:
for line in f:
print([Link]())

3. Working with CSV & JSON


import csv, json

with open("[Link]", "w", newline="") as f:


writer = [Link](f)
[Link](["name", "age"])
[Link](["Alice", 25])

data = {"name": "Alice", "age": 25}


with open("[Link]", "w") as f:
[Link](data, f)

4. Exception Handling
Use try/except to handle errors gracefully instead of crashing the program.

try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("That's not a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Result:", result)
finally:
print("Done.")

5. Modules & Packages


Modules let you organize and reuse code across files.

# [Link]
def add(a, b):
return a + b

# [Link]
import mymath
print([Link](3, 4)) # 7

from mymath import add


print(add(5, 6)) # 11

Commonly used standard-library modules:

• os — interact with the operating system

• datetime — work with dates and times

• random — generate random numbers

• math — mathematical functions

• re — regular expressions

6. Virtual Environments & pip


python -m venv venv
source venv/bin/activate # Linux/Mac
pip install requests

Practice Exercises
• Write a program that reads a text file and counts the number of words in it.

• Write a function that safely divides two numbers and handles exceptions.

• Create a small module with utility functions and import it into another script.

You might also like