File I/O & Module System
Read and write files, and learn how to organize code using Python modules and packages.
Working with Files
The with statement ensures files are properly closed even if an error occurs.
# Writing to a file
with open("hello.txt", "w") as f:
f.write("Hello from Python!")
# Reading from a file
with open("hello.txt", "r") as f:
data = f.read()
print(data)
with open("hello.txt", "w") as f:
f.write("Hello from Python!")
# Reading from a file
with open("hello.txt", "r") as f:
data = f.read()
print(data)
The Module System
Modules are Python files containing code. Use import to bring them into your script.
import math
import sys
from datetime import datetime
print(math.sqrt(16))
print(datetime.now())
import sys
from datetime import datetime
print(math.sqrt(16))
print(datetime.now())
Standard Library Highlights
osandpathlib: File system and path manipulations.json: Parsing and creating JSON data.random: Generating random numbers and choices.re: Regular expressions for advanced text matching.
External Packages (pip)
Install community libraries using pip, the Python package installer.
$ pip install requests
$ pip install pandas
$ pip install pandas
โ Practice (15 minutes)
- Write a script that creates a file called
names.txtand writes 3 names to it. - Modify the script to read
names.txtand print each name in uppercase. - Use the
randommodule to pick a random name from the list. - Import
osand useos.getcwd()to print your current directory.