JavaScript – Chapter 2: Development Environment
Learn what JavaScript is, where it runs, why it is important, and how beginners can start using it with simple examples and clear output.
Main reading content
Chapter 31: Essential Standard Library Modules
A complete beginner-friendly introduction to important Python standard library modules for files, folders, mathematics, statistics, security, collections, data organization, and practical automation.
Chapter 31 Topics
- 31.1 Introduction to the Standard Library
- 31.2
os - 31.3
sys - 31.4
pathlib - 31.5
shutil - 31.6
glob - 31.7
fnmatch - 31.8
math - 31.9
statistics - 31.10
decimal - 31.11
fractions - 31.12
random - 31.13
secrets - 31.14
string - 31.15
collections - 31.16
collections.abc - 31.17
heapq - 31.18
bisect - 31.19
array - 31.20
copy - 31.21
pprint - 31.22
textwrap - 31.23
enum - 31.24
dataclasses - 31.25 Practical Standard Library Projects
- 31.26 Chapter Practice Exercises
31.1 Introduction to the Standard Library
```The Python standard library is a large collection of modules included with Python. These modules provide ready-made tools for working with files, folders, dates, mathematics, text, collections, networks, databases, operating systems, and many other programming tasks.
Because standard library modules are included with Python, you normally do not need to install them with pip. You import only the modules needed by your program. Using built-in modules saves time, reduces repeated code, and gives you well-tested tools.
Example
# Import two standard library modules
```
import math
import statistics
numbers = [4, 9, 16, 25]
# Use the math module
print("Square root of 25:", math.sqrt(25))
# Use the statistics module
print("Average:", statistics.mean(numbers))
```
Output
Square root of 25: 5.0
```
Average: 13.5
```
Output Explanation
The math module calculates the square root of 25. The statistics module calculates the average of all values in the list. Both modules are available without installing additional packages.
31.2 os
```
The os module allows Python programs to interact with the operating system. It can read environment variables, create folders, rename files, remove files, list folder contents, and inspect the current working directory.
This module works across Windows, macOS, and Linux, although some features may behave differently between systems. For newer file-path operations, pathlib is often easier to read, but os remains widely used.
Example
import os
```
# Display the current folder
current_folder = os.getcwd()
print("Current folder:", current_folder)
# Create a new folder if it does not already exist
folder_name = "python_examples"
if not os.path.exists(folder_name):
os.mkdir(folder_name)
print("Folder created:", folder_name)
else:
print("Folder already exists:", folder_name)
# Display items in the current folder
items = os.listdir(".")
print("Number of items:", len(items))
```
Example Output
Current folder: /Users/student/python-course
```
Folder created: python_examples
Number of items: 8
```
Output Explanation
The exact folder path and item count depend on the computer. The program checks whether the folder exists before creating it, which prevents an error caused by trying to create the same folder twice.
```31.3 sys
```
The sys module provides information and tools related to the Python interpreter. It can show the Python version, command-line arguments, module search paths, platform information, and program exit controls.
Command-line programs often use sys.argv to receive information typed after the script name. The first item is usually the script filename, and later items are the values supplied by the user.
Example
import sys
```
print("Python version:")
print(sys.version)
print()
print("Platform:", sys.platform)
print()
print("Command-line arguments:")
print(sys.argv)
```
Example Output
Python version:
```
3.13.1
Platform: darwin
Command-line arguments:
['system_info.py']
```
Command-Line Example
import sys
```
if len(sys.argv) < 2:
print("Please provide your name.")
sys.exit()
name = sys.argv[1]
print("Hello,", name)
```
Run Command
python greeting.py Michael
Output
Hello, Michael
Output Explanation
The program checks whether a name was supplied. If no name is present, it ends with sys.exit(). When a name is supplied, it appears in sys.argv[1].
31.4 pathlib
```
The pathlib module provides an object-oriented way to work with file and folder paths. Instead of manually joining strings, you create Path objects and use operators and methods to navigate the file system.
It can create folders, read and write files, inspect file names and extensions, search paths, and check whether a path exists. It is often clearer and safer than older path-handling techniques.
Example
from pathlib import Path
```
# Create a Path object for a folder
folder = Path("course_files")
# Create the folder if necessary
folder.mkdir(exist_ok=True)
# Create a path for a text file
file_path = folder / "lesson.txt"
# Write text to the file
file_path.write_text(
"Learning pathlib is useful.",
encoding="utf-8"
)
# Read the file
content = file_path.read_text(encoding="utf-8")
print("File name:", file_path.name)
print("File extension:", file_path.suffix)
print("File exists:", file_path.exists())
print("Content:", content)
```
Output
File name: lesson.txt
```
File extension: .txt
File exists: True
Content: Learning pathlib is useful.
```
Output Explanation
The slash operator joins the folder and filename. The module creates the folder, writes text, reads it again, and provides information about the path.
```31.5 shutil
```
The shutil module provides high-level file and folder operations. It can copy files, copy complete folder trees, move items, remove directories, and create compressed archives.
These operations can change or delete real files, so paths should be checked carefully. It is a good practice to test file-management scripts inside a temporary practice folder before using them with important files.
Example
from pathlib import Path
```
import shutil
source = Path("original.txt")
destination = Path("backup.txt")
# Create the source file
source.write_text(
"Important course notes",
encoding="utf-8"
)
# Copy the file and its metadata
shutil.copy2(source, destination)
print("Source exists:", source.exists())
print("Backup exists:", destination.exists())
print("Backup content:", destination.read_text(encoding="utf-8"))
```
Output
Source exists: True
```
Backup exists: True
Backup content: Important course notes
```
Output Explanation
The source file is created first. The copy2() function makes a copy and tries to preserve file metadata. The backup contains the same text as the original.
31.6 glob
```
The glob module searches for file and folder names that match wildcard patterns. An asterisk matches many characters, a question mark matches one character, and square brackets can describe character choices.
Glob patterns are useful for finding all text files, images, reports, or files following a naming rule. The module returns paths that match the requested pattern.
Example
import glob
```
from pathlib import Path
# Create some example files
Path("lesson1.txt").write_text("Lesson 1", encoding="utf-8")
Path("lesson2.txt").write_text("Lesson 2", encoding="utf-8")
Path("notes.pdf").write_text("Example PDF name", encoding="utf-8")
# Find all files ending in .txt
text_files = glob.glob("*.txt")
print("Text files:")
for filename in text_files:
print("-", filename)
```
Example Output
Text files:
```
* lesson1.txt
* lesson2.txt
* original.txt
* backup.txt
Output Explanation
The exact result depends on which text files already exist in the folder. The pattern *.txt means any filename ending with .txt.
31.7 fnmatch
The fnmatch module checks whether filenames or ordinary strings match wildcard patterns. It is related to glob, but it does not search the file system by itself.
You provide the filename and pattern directly. This is useful when you already have a collection of names and want to filter them using familiar wildcard rules.
Example
import fnmatch
files = [
"report_january.csv",
"report_february.csv",
"photo.jpg",
"notes.txt"
]
matching_files = [
filename
for filename in files
if fnmatch.fnmatch(filename, "report_*.csv")
]
print(matching_files)
```
Output
['report_january.csv', 'report_february.csv']
Output Explanation
The pattern requires the filename to begin with report_ and end with .csv. Only the two report files follow that rule.
31.8 math
```
The math module provides mathematical constants and functions for real numbers. It includes square roots, powers, rounding, factorials, trigonometry, logarithms, distances, and constants such as pi and e.
Many operations can be performed with basic Python operators, but math provides more specialized and precise tools. Most functions return floating-point values.
Example
import math
```
radius = 5
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius
print("Square root of 81:", math.sqrt(81))
print("Factorial of 5:", math.factorial(5))
print("Area:", round(area, 2))
print("Circumference:", round(circumference, 2))
print("Rounded up:", math.ceil(4.2))
print("Rounded down:", math.floor(4.8))
```
Output
Square root of 81: 9.0
```
Factorial of 5: 120
Area: 78.54
Circumference: 31.42
Rounded up: 5
Rounded down: 4
```
Output Explanation
The module calculates a square root, factorial, circle measurements, and directional rounding. The round() function limits the circle results to two decimal places.
31.9 statistics
```
The statistics module provides common calculations used when analyzing numeric data. It can calculate the mean, median, mode, variance, and standard deviation.
These functions are useful for grades, sales, measurements, survey results, and other collections of numbers. You should understand what each calculation means before using it in a report.
Example
import statistics
```
scores = [80, 85, 90, 90, 95]
print("Mean:", statistics.mean(scores))
print("Median:", statistics.median(scores))
print("Mode:", statistics.mode(scores))
print("Population standard deviation:", round(
statistics.pstdev(scores),
2
))
```
Output
Mean: 88
```
Median: 90
Mode: 90
Population standard deviation: 5.1
```
Output Explanation
The mean is the arithmetic average. The median is the middle value after sorting. The mode is the most repeated value. Standard deviation measures how spread out the scores are.
```31.10 decimal
```
The decimal module performs decimal arithmetic with greater control than ordinary floating-point numbers. It is especially useful for money and calculations where decimal rounding must be predictable.
Decimal values should usually be created from strings. Creating them from floating-point values may carry existing binary approximation into the decimal result.
Example
from decimal import Decimal, ROUND_HALF_UP
```
price = Decimal("19.99")
quantity = Decimal("3")
tax_rate = Decimal("0.13")
subtotal = price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
# Round to two decimal places
money_unit = Decimal("0.01")
tax = tax.quantize(
money_unit,
rounding=ROUND_HALF_UP
)
total = total.quantize(
money_unit,
rounding=ROUND_HALF_UP
)
print("Subtotal:", subtotal)
print("Tax:", tax)
print("Total:", total)
```
Output
Subtotal: 59.97
```
Tax: 7.80
Total: 67.77
```
Output Explanation
The program uses decimal strings and explicitly rounds monetary values to two decimal places. This provides controlled financial arithmetic.
```31.11 fractions
```
The fractions module represents rational numbers as exact fractions. A fraction contains a numerator and denominator and is automatically reduced to its simplest form.
Fractions are useful in mathematics, measurements, recipes, ratios, and situations where exact fractional values are preferred over decimal approximations.
Example
from fractions import Fraction
```
first = Fraction(1, 3)
second = Fraction(1, 6)
total = first + second
print("First fraction:", first)
print("Second fraction:", second)
print("Total:", total)
print("Decimal value:", float(total))
```
Output
First fraction: 1/3
```
Second fraction: 1/6
Total: 1/2
Decimal value: 0.5
```
Output Explanation
The module adds the fractions exactly and simplifies the result to one-half. The final line converts the fraction to a floating-point value.
```31.12 random
```
The random module produces pseudo-random values. It can generate numbers, select items, shuffle lists, and create random samples.
It is suitable for games, simulations, classroom exercises, and testing. It should not be used for passwords, security tokens, or other security-sensitive values because its output is not designed to resist prediction.
Example
import random
```
names = ["Ali", "Sara", "Michael", "Emma"]
random_number = random.randint(1, 10)
selected_name = random.choice(names)
random.shuffle(names)
sample = random.sample(names, 2)
print("Random number:", random_number)
print("Selected name:", selected_name)
print("Shuffled names:", names)
print("Random sample:", sample)
```
Example Output
Random number: 7
```
Selected name: Sara
Shuffled names: ['Emma', 'Michael', 'Ali', 'Sara']
Random sample: ['Ali', 'Emma']
```
Output Explanation
The output changes between runs. randint() includes both endpoints, choice() selects one item, shuffle() changes the original list order, and sample() selects unique items.
31.13 secrets
```
The secrets module generates values suitable for security-sensitive applications. It can create random tokens, secure choices, and cryptographically stronger random values.
Use this module for password-reset links, session tokens, invitation codes, and secure identifiers. It is preferred over random when unpredictability matters.
Example
import secrets
```
import string
alphabet = (
string.ascii_letters
+ string.digits
)
secure_code = "".join(
secrets.choice(alphabet)
for _ in range(12)
)
url_token = secrets.token_urlsafe(16)
print("Secure code:", secure_code)
print("URL-safe token:", url_token)
```
Example Output
Secure code: q8Fd2Lm9Xr4P
```
URL-safe token: sZm4jL7Rz35jZJw6qSnvcQ
```
Output Explanation
Both values change on every run. The first is assembled from securely selected letters and digits. The second is created as a URL-safe token.
```31.14 string
```
The string module provides useful character collections and text tools. Common constants include lowercase letters, uppercase letters, digits, punctuation, whitespace, and printable characters.
These constants are useful when validating text, generating codes, filtering characters, or building custom alphabets. The module also contains the Template class for simple placeholder substitution.
Example
import string
```
print("Lowercase:", string.ascii_lowercase)
print("Uppercase:", string.ascii_uppercase)
print("Digits:", string.digits)
text = "Room A12 costs $250."
letters_only = "".join(
character
for character in text
if character in string.ascii_letters or character == " "
)
print("Letters only:", letters_only)
```
Output
Lowercase: abcdefghijklmnopqrstuvwxyz
```
Uppercase: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Digits: 0123456789
Letters only: Room A costs
```
Template Example
from string import Template
```
message_template = Template(
"Hello $name, your order number is $order."
)
message = message_template.substitute(
name="Sara",
order="A105"
)
print(message)
```
Output
Hello Sara, your order number is A105.
```
31.15 collections
```
The collections module provides specialized container types. Important tools include Counter, defaultdict, deque, namedtuple, and ChainMap.
These classes solve common collection problems more clearly than manually building the same behavior with ordinary lists and dictionaries.
Example: Counter
from collections import Counter
```
words = [
"python",
"html",
"python",
"css",
"python",
"html"
]
counts = Counter(words)
print(counts)
print("Python count:", counts["python"])
print("Most common:", counts.most_common(2))
```
Output
Counter({'python': 3, 'html': 2, 'css': 1})
```
Python count: 3
Most common: [('python', 3), ('html', 2)]
```
Example: defaultdict
from collections import defaultdict
```
students_by_grade = defaultdict(list)
students_by_grade["A"].append("Sara")
students_by_grade["B"].append("Michael")
students_by_grade["A"].append("Ali")
print(dict(students_by_grade))
```
Output
{'A': ['Sara', 'Ali'], 'B': ['Michael']}
Example: deque
from collections import deque
```
tasks = deque(["Task 1", "Task 2"])
tasks.append("Task 3")
tasks.appendleft("Urgent Task")
print(tasks)
print("Completed:", tasks.popleft())
print("Remaining:", tasks)
```
Output
deque(['Urgent Task', 'Task 1', 'Task 2', 'Task 3'])
```
Completed: Urgent Task
Remaining: deque(['Task 1', 'Task 2', 'Task 3'])
31.16 collections.abc
```
The collections.abc module contains abstract base classes representing common collection behaviors. Examples include Iterable, Iterator, Sequence, Mapping, and Set.
These classes are useful when checking whether an object supports a general behavior instead of checking for one specific type. For example, both lists and tuples are sequences.
Example
from collections.abc import (
Iterable,
Sequence,
Mapping
```
)
values = [
[1, 2, 3],
(4, 5),
{"name": "Sara"},
100
]
for value in values:
print("Value:", value)
print("Iterable:", isinstance(value, Iterable))
print("Sequence:", isinstance(value, Sequence))
print("Mapping:", isinstance(value, Mapping))
print()
```
Output
Value: [1, 2, 3]
```
Iterable: True
Sequence: True
Mapping: False
Value: (4, 5)
Iterable: True
Sequence: True
Mapping: False
Value: {'name': 'Sara'}
Iterable: True
Sequence: False
Mapping: True
Value: 100
Iterable: False
Sequence: False
Mapping: False
```
Output Explanation
Lists and tuples are sequences. A dictionary is a mapping and is also iterable. An integer does not support iteration.
```31.17 heapq
```
The heapq module implements a min-heap priority queue. In a min-heap, the smallest value is always available at the first position.
Heaps are useful for task scheduling, finding the smallest values, processing priorities, and algorithms that repeatedly need the next smallest item.
Example
import heapq
```
numbers = [8, 3, 10, 1, 6]
# Convert the list into a heap
heapq.heapify(numbers)
print("Heap:", numbers)
# Add another value
heapq.heappush(numbers, 2)
print("After adding 2:", numbers)
# Remove the smallest value
smallest = heapq.heappop(numbers)
print("Smallest:", smallest)
print("Remaining heap:", numbers)
print("Three smallest:", heapq.nsmallest(3, numbers))
```
Example Output
Heap: [1, 3, 10, 8, 6]
```
After adding 2: [1, 3, 2, 8, 6, 10]
Smallest: 1
Remaining heap: [2, 3, 10, 8, 6]
Three smallest: [2, 3, 6]
```
Output Explanation
The complete internal list is not always fully sorted. The important rule is that the smallest item remains accessible at the first position.
```31.18 bisect
```
The bisect module works with sorted lists. It finds the correct insertion position for a new value and can insert the value while keeping the list sorted.
This is useful when a program repeatedly adds values to a list that must remain ordered. It avoids manually searching every position.
Example
import bisect
```
scores = [60, 70, 80, 90]
new_score = 75
position = bisect.bisect_left(
scores,
new_score
)
print("Insertion position:", position)
bisect.insort(scores, new_score)
print("Updated scores:", scores)
```
Output
Insertion position: 2
```
Updated scores: [60, 70, 75, 80, 90]
```
Output Explanation
Index 2 is the correct position before 80. The insort() function inserts the score while preserving sorted order.
31.19 array
```
The array module provides compact collections of values that all share the same basic type. Unlike a normal list, an array is created with a type code that controls which values it stores.
Arrays can use less memory than lists for large numeric collections. However, normal lists are more flexible and are sufficient for many beginner programs.
Example
from array import array
```
# Type code "i" means signed integers
numbers = array("i", [10, 20, 30])
numbers.append(40)
numbers.extend([50, 60])
print("Array:", numbers)
print("First value:", numbers[0])
numbers.remove(30)
print("After removal:", numbers)
```
Output
Array: array('i', [10, 20, 30, 40, 50, 60])
```
First value: 10
After removal: array('i', [10, 20, 40, 50, 60])
```
Output Explanation
The array accepts integer values because it uses the i type code. It supports familiar operations such as appending, extending, indexing, and removing.
31.20 copy
```
The copy module creates shallow and deep copies of Python objects. A shallow copy creates a new outer container but may continue sharing nested objects. A deep copy recursively copies nested structures.
Understanding this difference is important when working with lists containing dictionaries, lists, or other mutable objects. Changing nested data in a shallow copy may also affect the original.
Example
import copy
```
original = [
["Ali", 85],
["Sara", 92]
]
shallow_copy = copy.copy(original)
deep_copy = copy.deepcopy(original)
# Change a nested value in the shallow copy
shallow_copy[0][1] = 100
# Change a nested value in the deep copy
deep_copy[1][1] = 75
print("Original:", original)
print("Shallow copy:", shallow_copy)
print("Deep copy:", deep_copy)
```
Output
Original: [['Ali', 100], ['Sara', 92]]
```
Shallow copy: [['Ali', 100], ['Sara', 92]]
Deep copy: [['Ali', 85], ['Sara', 75]]
```
Output Explanation
The shallow copy shares the inner lists, so changing Ali's score also changes the original. The deep copy has separate inner lists, so changing Sara's score does not affect the original.
```31.21 pprint
```
The pprint module means pretty print. It displays nested lists and dictionaries in a more readable format than a basic print() call.
It is useful during debugging, learning, and data inspection. You can control width, indentation, sorting, and formatting.
Example
from pprint import pprint
```
students = {
"class_name": "Python Beginners",
"students": [
{
"name": "Sara",
"scores": [90, 92, 95]
},
{
"name": "Michael",
"scores": [78, 84, 81]
}
]
}
pprint(
students,
width=50,
sort_dicts=False
)
```
Output
{'class_name': 'Python Beginners',
```
'students': [{'name': 'Sara',
'scores': [90, 92, 95]},
{'name': 'Michael',
'scores': [78, 84, 81]}]}
```
Output Explanation
The structure is arranged across several lines with indentation, making the nested values easier to understand.
```31.22 textwrap
```
The textwrap module formats long text into shorter lines. It can wrap paragraphs, indent text, shorten content, remove common indentation, and create readable terminal output.
It is useful for command-line applications, reports, help messages, receipts, and other text-based interfaces.
Example
import textwrap
```
paragraph = (
"Python includes a large standard library "
"that provides tools for many common "
"programming tasks."
)
wrapped_text = textwrap.fill(
paragraph,
width=35
)
print(wrapped_text)
print()
print(textwrap.indent(
wrapped_text,
prefix="> "
))
```
Output
Python includes a large standard
```
library that provides tools for
many common programming tasks.
> Python includes a large standard
> library that provides tools for
> many common programming tasks.
```
Output Explanation
The fill() function wraps the paragraph to approximately 35 characters per line. The indent() function adds a prefix to each line.
31.23 enum
```
The enum module creates named sets of constant values. Enumerations make code clearer when a variable should contain one value from a known group, such as order status, user role, traffic-light state, or difficulty level.
Instead of using unexplained numbers or strings throughout a program, an enum provides descriptive names and reduces spelling mistakes.
Example
from enum import Enum, auto
```
class OrderStatus(Enum):
PENDING = auto()
PROCESSING = auto()
SHIPPED = auto()
DELIVERED = auto()
current_status = OrderStatus.SHIPPED
print("Status name:", current_status.name)
print("Status value:", current_status.value)
if current_status is OrderStatus.SHIPPED:
print("The order is on its way.")
```
Example Output
Status name: SHIPPED
```
Status value: 3
The order is on its way.
```
Output Explanation
The auto() function automatically assigns values. The program uses the descriptive enum member instead of a plain string or unexplained number.
31.24 dataclasses
```
The dataclasses module reduces repeated code in classes that mainly store data. The @dataclass decorator can automatically create methods such as __init__(), __repr__(), and __eq__().
Data classes are useful for products, students, orders, settings, coordinates, and other structured records. Type annotations describe the expected fields.
Example
from dataclasses import dataclass, field
```
@dataclass
class Product:
name: str
price: float
quantity: int = 1
tags: list[str] = field(default_factory=list)
```
def total(self):
return self.price * self.quantity
```
keyboard = Product(
name="Keyboard",
price=49.99,
quantity=2,
tags=["computer", "accessory"]
)
print(keyboard)
print("Total:", keyboard.total())
```
Output
Product(name='Keyboard', price=49.99, quantity=2, tags=['computer', 'accessory'])
```
Total: 99.98
```
Output Explanation
Python automatically creates the initializer and readable object representation. The custom total() method calculates the value of all product units.
31.25 Practical Standard Library Projects
```
Standard library modules become most useful when several of them work together. A file-management program may combine pathlib, shutil, glob, collections, and datetime.
The following project organizes files into folders based on their extensions. It also creates a summary showing how many files were moved into each category.
Project: Automatic File Organizer
from pathlib import Path
```
from collections import Counter
import shutil
# Create a practice folder
source_folder = Path("practice_downloads")
source_folder.mkdir(exist_ok=True)
# Create sample files
sample_files = [
"photo1.jpg",
"photo2.png",
"report.pdf",
"notes.txt",
"data.csv",
"music.mp3",
"unknown.xyz"
]
for filename in sample_files:
file_path = source_folder / filename
```
if not file_path.exists():
file_path.write_text(
"Sample file",
encoding="utf-8"
)
```
# Map file extensions to folder names
categories = {
".jpg": "Images",
".jpeg": "Images",
".png": "Images",
".gif": "Images",
".pdf": "Documents",
".txt": "Documents",
".docx": "Documents",
".csv": "Data",
".xlsx": "Data",
".mp3": "Audio",
".wav": "Audio"
}
moved_counts = Counter()
# Process every file in the source folder
for file_path in source_folder.iterdir():
if not file_path.is_file():
continue
```
extension = file_path.suffix.lower()
category = categories.get(
extension,
"Other"
)
category_folder = source_folder / category
category_folder.mkdir(exist_ok=True)
destination = category_folder / file_path.name
shutil.move(
str(file_path),
str(destination)
)
moved_counts[category] += 1
print(
"Moved:",
file_path.name,
"->",
category
)
```
print()
print("ORGANIZATION SUMMARY")
print("-" * 40)
for category, count in sorted(moved_counts.items()):
print(category, ":", count)
```
Output
Moved: photo1.jpg -> Images
```
Moved: photo2.png -> Images
Moved: report.pdf -> Documents
Moved: notes.txt -> Documents
Moved: data.csv -> Data
Moved: music.mp3 -> Audio
Moved: unknown.xyz -> Other
## ORGANIZATION SUMMARY
Audio : 1
Data : 1
Documents : 2
Images : 2
Other : 1
```
Project Explanation
The Path class creates and inspects folders and files. A dictionary maps extensions to category names. Unknown extensions use the Other category.
The shutil.move() function moves each file into its category folder. A Counter records how many files were moved into each category.
How to Run the Project
- Create a file named
file_organizer.py. - Copy the complete program into the file.
- Save the file.
- Open a terminal in the same folder.
- Run
python file_organizer.py. - On some computers, run
python3 file_organizer.py. - Open the created
practice_downloadsfolder. - Review the category folders and moved files.
Project Challenges
- Add video categories.
- Create a backup before moving files.
- Prevent overwriting duplicate filenames.
- Add the current date to category folders.
- Search through subfolders recursively.
- Create a text report.
- Display file sizes.
- Sort large and small files separately.
- Use
fnmatchfor custom rules. - Create a command-line source-folder argument.
31.26 Chapter Practice Exercises
```These exercises help you practise the essential standard library modules covered in this chapter. Complete the simpler exercises first, and then combine several modules in larger programs.
- Use
os.getcwd()to display the current folder. - Create and remove a practice folder with
os. - Display the Python version using
sys. - Read a command-line name with
sys.argv. - Create a folder and file using
pathlib. - Display a path's name, stem, suffix, and parent.
- Copy a file using
shutil.copy2(). - Move a file into another folder.
- Find every text file with
glob. - Filter report filenames using
fnmatch. - Calculate a circle's area using
math.pi. - Calculate square roots and factorials.
- Find the mean, median, and mode of a score list.
- Calculate money totals using
Decimal. - Add and subtract exact fractions.
- Create a random dice game.
- Shuffle a list of student names.
- Generate a secure token with
secrets. - Create a secure code using letters and digits.
- Use
string.ascii_lettersto filter text. - Create a message using
string.Template. - Count repeated words with
Counter. - Group names with
defaultdict. - Create a task queue with
deque. - Check whether values are iterable or mappings.
- Create a priority queue with
heapq. - Keep a score list sorted with
bisect. - Create an integer array and calculate its total.
- Compare shallow and deep copies.
- Pretty-print a nested dictionary.
- Wrap a paragraph to 40 characters.
- Create an enum for user roles.
- Create a data class for a student.
- Create a data class for an order.
- Build a file organizer using several modules.
- Build a secure code generator.
- Build a student statistics report.
- Build a command-line calculator.
- Build a sorted priority-task manager.
- Build a backup utility using
pathlibandshutil.
Practice Example: Student Statistics Report
from dataclasses import dataclass
```
from collections import Counter
import statistics
@dataclass
class Student:
name: str
score: float
```
@property
def grade(self):
if self.score >= 90:
return "A"
if self.score >= 80:
return "B"
if self.score >= 70:
return "C"
if self.score >= 60:
return "D"
return "F"
```
students = [
Student("Sara", 92),
Student("Michael", 81),
Student("Ali", 92),
Student("Emma", 68),
Student("David", 75)
]
scores = [
student.score
for student in students
]
grade_counts = Counter(
student.grade
for student in students
)
print("STUDENT REPORT")
print("-" * 40)
for student in students:
print(
student.name,
"- Score:",
student.score,
"- Grade:",
student.grade
)
print()
print("Average:", statistics.mean(scores))
print("Median:", statistics.median(scores))
print("Highest:", max(scores))
print("Lowest:", min(scores))
print("Grade counts:", grade_counts)
```
Output
STUDENT REPORT
```
---
Sara - Score: 92 - Grade: A
Michael - Score: 81 - Grade: B
Ali - Score: 92 - Grade: A
Emma - Score: 68 - Grade: D
David - Score: 75 - Grade: C
Average: 81.6
Median: 81
Highest: 92
Lowest: 68
Grade counts: Counter({'A': 2, 'B': 1, 'D': 1, 'C': 1})
```
Output Explanation
The data class stores each student's name and score. The property calculates a letter grade. The statistics module creates summary values, while Counter counts how many students received each grade.
A modern course built to help learners study step by step with clarity, comfort, and confidence.