Пример 1. Чтение и парсинг файла
Этот пример показывает, как прочитать файл, разобрать строки и собрать список записей.
# example_01_read.py
import os
import sys
from collections import defaultdict
def read_sales_data(file_path):
"""Считывает данные из .txt файла и возвращает список записей."""
with open(file_path, "r", encoding="utf-8") as file:
lines = file.readlines()
sales = []
for line in lines:
parts = line.strip().split(",")
if len(parts) == 5:
name, date, amount, category, city = parts
year, month, day = date.split("-")
sales.append({
"name": name,
"date": date,
"amount": int(amount),
"category": category,
"year": year,
"month": month,
"day": day,
})
return sales
# Проверка на небольшом файле
sample_data = """Olivia Suarez,2024-08-02,4565,Electronics,Dallas
Jennifer Jacobs,2023-08-19,4963,Automotive,London
Erin Johnson,2024-08-29,1796,Clothing,Miami"""
with open("sample_sales.txt", "w", encoding="utf-8") as f:
f.write(sample_data)
records = read_sales_data("sample_sales.txt")
for record in records:
print(record)
os.remove("sample_sales.txt")
Пример 2. Группировка через defaultdict
Здесь показано, как сгруппировать записи и суммы по периодам и категориям.
# example_02_group.py
from collections import defaultdict
sales = [
{"name": "Olivia Suarez", "date": "2024-08-02", "amount": 4565,
"category": "Electronics", "year": "2024", "month": "08"},
{"name": "Erin Johnson", "date": "2024-08-29", "amount": 1796,
"category": "Clothing", "year": "2024", "month": "08"},
{"name": "Jennifer Jacobs", "date": "2023-08-19", "amount": 4963,
"category": "Automotive", "year": "2023", "month": "08"},
]
grouped_sales = defaultdict(list)
category_totals = defaultdict(lambda: defaultdict(int))
for record in sales:
key = (record["year"], record["month"], record["category"])
grouped_sales[key].append(record)
category_totals[(record["year"], record["month"])][record["category"]] += record["amount"]
print("Группы записей:")
for key, records in grouped_sales.items():
print(key, "->", len(records), "записей")
print("\nСуммы по категориям:")
for key, totals in category_totals.items():
print(key, "->", dict(totals))
Пример 3. Создание категориальных отчётов
Пример записи файлов для каждой категории с сортировкой по дате.
# example_03_category_reports.py
import os
from collections import defaultdict
def write_category_reports(output_dir, grouped_sales):
"""Создаёт файлы с отчётами по категориям, сортируя записи по дате."""
for (year, month, category), records in grouped_sales.items():
category_file = os.path.join(output_dir, year, month, f"{category}.txt")
os.makedirs(os.path.dirname(category_file), exist_ok=True)
sorted_records = sorted(records, key=lambda x: x["date"])
with open(category_file, "w", encoding="utf-8") as file:
for record in sorted_records:
file.write(f"{record['date']},{record['name']},{record['amount']}\n")
# Тестовые данные
grouped = defaultdict(list)
grouped[("2025", "02", "Electronics")] = [
{"date": "2025-02-02", "name": "Rachel Miller", "amount": 1097},
{"date": "2025-02-01", "name": "Cynthia Maddox", "amount": 538},
{"date": "2025-02-01", "name": "Kendra Martinez", "amount": 3799},
]
write_category_reports("example_reports", grouped)
# Проверим содержимое
with open("example_reports/2025/02/Electronics.txt", "r", encoding="utf-8") as f:
print(f.read())
# Удалим тестовую папку
import shutil
shutil.rmtree("example_reports")
Пример 4. Создание месячных отчётов
Пример формирования monthly_report.txt с суммами по категориям.
# example_04_monthly_reports.py
import os
from collections import defaultdict
def write_monthly_reports(output_dir, category_totals):
"""Создаёт общий отчёт по каждому месяцу."""
for (year, month), category_sums in category_totals.items():
report_file = os.path.join(output_dir, year, month, "monthly_report.txt")
os.makedirs(os.path.dirname(report_file), exist_ok=True)
with open(report_file, "w", encoding="utf-8") as file:
for category, total in sorted(category_sums.items()):
file.write(f"{category},{total}\n")
file.write(f"Full,{sum(category_sums.values())}\n")
category_totals = defaultdict(lambda: defaultdict(int))
category_totals[("2025", "02")]["Electronics"] = 79403
category_totals[("2025", "02")]["Clothing"] = 102001
category_totals[("2025", "02")]["Groceries"] = 104387
write_monthly_reports("example_reports", category_totals)
with open("example_reports/2025/02/monthly_report.txt", "r", encoding="utf-8") as f:
print(f.read())
import shutil
shutil.rmtree("example_reports")
Пример 5. Полная программа
Рабочая версия программы, объединяющая все шаги. Подробное решение с комментариями находится в разделе Решения.
# sales_report.py
import os
import sys
from collections import defaultdict
def read_sales_data(file_path):
"""Считывает данные из .txt файла и возвращает список записей."""
with open(file_path, "r", encoding="utf-8") as file:
lines = file.readlines()
sales = []
for line in lines:
parts = line.strip().split(",")
if len(parts) == 5:
name, date, amount, category, city = parts
year, month, day = date.split("-")
sales.append({
"name": name,
"date": date,
"amount": int(amount),
"category": category,
"year": year,
"month": month,
"day": day,
})
return sales
def write_category_reports(output_dir, grouped_sales):
"""Создаёт файлы с отчётами по категориям, сортируя записи по дате."""
for (year, month, category), records in grouped_sales.items():
category_file = os.path.join(output_dir, year, month, f"{category}.txt")
os.makedirs(os.path.dirname(category_file), exist_ok=True)
sorted_records = sorted(records, key=lambda x: x["date"])
with open(category_file, "w", encoding="utf-8") as file:
for record in sorted_records:
file.write(f"{record['date']},{record['name']},{record['amount']}\n")
def write_monthly_reports(output_dir, category_totals):
"""Создаёт общий отчёт по каждому месяцу."""
for (year, month), category_sums in category_totals.items():
report_file = os.path.join(output_dir, year, month, "monthly_report.txt")
os.makedirs(os.path.dirname(report_file), exist_ok=True)
with open(report_file, "w", encoding="utf-8") as file:
for category, total in sorted(category_sums.items()):
file.write(f"{category},{total}\n")
file.write(f"Full,{sum(category_sums.values())}\n")
def process_sales_data(file_path, output_dir):
"""Обрабатывает продажи и создаёт отчёты."""
sales = read_sales_data(file_path)
grouped_sales = defaultdict(list)
category_totals = defaultdict(lambda: defaultdict(int))
for record in sales:
key = (record["year"], record["month"], record["category"])
grouped_sales[key].append(record)
category_totals[(record["year"], record["month"])][record["category"]] += record["amount"]
write_category_reports(output_dir, grouped_sales)
write_monthly_reports(output_dir, category_totals)
if len(sys.argv) < 3:
print("Usage: python sales_report.py <input_file> <output_directory>")
sys.exit(1)
input_file = sys.argv[1]
output_directory = sys.argv[2]
process_sales_data(input_file, output_directory)
print("Reports generated successfully!")
Как запустить в VS Code
- Создайте файл
sales_data.txtс несколькими строками форматаимя,дата,сумма,категория,город. - Создайте файл
sales_report.pyи скопируйте в него полную программу из примера 5. - Откройте терминал в VS Code (Ctrl + `).
- Убедитесь, что активировано виртуальное окружение.
- Запустите:
python sales_report.py data/sales_data.txt reports - Проверьте созданную папку
reports/и файлы внутри.