๐Ÿ Python Examples - Comprehensive Code Library
โ† Back to PranavKulkarni.org
Lesson 6 ยท Fundamentals

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)

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

Standard Library Highlights

  • os and pathlib: 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

โœ… Practice (15 minutes)

  • Write a script that creates a file called names.txt and writes 3 names to it.
  • Modify the script to read names.txt and print each name in uppercase.
  • Use the random module to pick a random name from the list.
  • Import os and use os.getcwd() to print your current directory.