/
santanas
/
YAPI_Homework
Обзор
Документация
Войти
/
santanas
/
YAPI_Homework
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
merge_files.py
46 строк
2 KB
Santana
Домашнее задание: работа с файлами (cook_book)
22 июл 2026, 19:27
22 июл 2026, 19:27
031df89
Код
Авторство
О чём код?
"""Задача №3. Объединение нескольких файлов в один с сортировкой по числу строк.""" import os def count_lines(file_path): """Возвращает количество строк в файле file_path.""" with open(file_path, 'r', encoding='utf-8') as file: return sum(1 for _ in file) def sort_files_by_lines_count(file_paths): """Возвращает file_paths, отсортированные по возрастанию числа строк в файле.""" return sorted(file_paths, key=count_lines) def append_file_with_header(source_path, output_file): """Дописывает в output_file имя файла, число строк и содержимое source_path.""" with open(source_path, 'r', encoding='utf-8') as source_file: lines = source_file.readlines() file_name = os.path.basename(source_path) output_file.write(f'{file_name}\n') output_file.write(f'{len(lines)}\n') output_file.writelines(lines) def merge_files(file_paths, output_path): """Объединяет файлы file_paths в output_path по правилам задачи №3.""" sorted_paths = sort_files_by_lines_count(file_paths) with open(output_path, 'w', encoding='utf-8') as output_file: for source_path in sorted_paths: append_file_with_header(source_path, output_file) def main(): """Точка входа: объединяет файлы из папки source_files в merged_result.txt.""" source_dir = 'source_files' file_names = sorted(os.listdir(source_dir)) file_paths = [os.path.join(source_dir, name) for name in file_names] merge_files(file_paths, 'merged_result.txt') if __name__ == '__main__': main()