/
Alex-Piton
/
Homework_open_file
Обзор
Документация
Войти
/
Alex-Piton
/
Homework_open_file
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Z3.py
44 строки
1 KB
Alex-Piton
upload files
26 июл 2025, 11:55
26 июл 2025, 11:55
52ac537
Код
Авторство
О чём код?
import os import errno def create_directory(path): try: os.makedirs(path) print(f"Директория {path} успешно создана") except OSError as e: if e.errno != errno.EEXIST: raise def merge_files(directory, output_file): # Создаем директорию, если её нет create_directory(directory) files_dict = {} for filename in os.listdir(directory): if filename.endswith('.txt'): file_path = os.path.join(directory, filename) with open(file_path, 'r', encoding='utf-8') as file: content = file.readlines() content = [line.strip() + '\n' for line in content if line.strip()] files_dict[filename] = content with open(output_file, 'w', encoding='utf-8') as outfile: for filename, content in sorted(files_dict.items(), key=lambda x: len(x[1])): outfile.write(f"{filename}\n") outfile.write(f"{len(content)}\n") outfile.writelines(content) outfile.write('\n') # Получаем директорию скрипта script_dir = os.path.dirname(os.path.abspath(__file__)) files_dir = os.path.join(script_dir, 'files') try: merge_files(files_dir, 'result.txt') print("Файлы успешно объединены") except FileNotFoundError as fnf_error: print(f"Ошибка: {fnf_error}") except Exception as e: print(f"Произошла ошибка: {str(e)}")