81 lines
2.6 KiB
Python
81 lines
2.6 KiB
Python
|
import os
|
|||
|
import random
|
|||
|
|
|||
|
# Путь к каталогу для поиска файла с наибольшим кол-вом строк
|
|||
|
CATALOG_PATH = "/var/data"
|
|||
|
|
|||
|
# Путь до файла с результатом
|
|||
|
RESULT_FILE = "/var/result/data.txt"
|
|||
|
|
|||
|
|
|||
|
def find_file_with_most_lines(directory):
|
|||
|
"""Ищет файл с наибольшим количеством строк в заданном каталоге и его подкаталогах."""
|
|||
|
|
|||
|
file_with_most_lines = None
|
|||
|
max_lines = 0
|
|||
|
|
|||
|
for root, _, files in os.walk(directory):
|
|||
|
for file in files:
|
|||
|
filepath = os.path.join(root, file)
|
|||
|
|
|||
|
try:
|
|||
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|||
|
line_count = sum(1 for _ in f)
|
|||
|
|
|||
|
if line_count > max_lines:
|
|||
|
max_lines = line_count
|
|||
|
file_with_most_lines = (filepath, line_count)
|
|||
|
|
|||
|
except (OSError, UnicodeDecodeError) as e:
|
|||
|
print(f"Ошибка при обработке файла '{filepath}': {e}")
|
|||
|
|
|||
|
return file_with_most_lines
|
|||
|
|
|||
|
|
|||
|
def copy_file(first, second):
|
|||
|
"""Копирует содержимое файла first в файл second."""
|
|||
|
|
|||
|
try:
|
|||
|
with open(second, "wb") as f_second, open(first, "rb") as f_first:
|
|||
|
while chunk := f_first.read(4096):
|
|||
|
f_second.write(chunk)
|
|||
|
|
|||
|
print(f"Файл '{first}' успешно скопирован в '{second}'.")
|
|||
|
|
|||
|
except Exception as e:
|
|||
|
print(f"Ошибка при копировании файла '{first}': {e}")
|
|||
|
|
|||
|
|
|||
|
def main():
|
|||
|
file_with_most_lines = find_file_with_most_lines(CATALOG_PATH)
|
|||
|
|
|||
|
if file_with_most_lines:
|
|||
|
first_path, _ = file_with_most_lines
|
|||
|
second_path = RESULT_FILE
|
|||
|
|
|||
|
copy_file(first_path, second_path)
|
|||
|
|
|||
|
else:
|
|||
|
print("Не найдены файлы")
|
|||
|
|
|||
|
|
|||
|
def generate_random_numbers(filename, count):
|
|||
|
"""Функция генерирует случайные числа и записывает их в файл"""
|
|||
|
|
|||
|
with open(filename, "w") as f:
|
|||
|
for _ in range(count):
|
|||
|
num = random.randint(0, 1000)
|
|||
|
f.write(str(num) + "\n")
|
|||
|
|
|||
|
print(f"Случайные числа успешно записаны в '{filename}'.")
|
|||
|
|
|||
|
|
|||
|
if __name__ == "__main__":
|
|||
|
generate_random_numbers("/var/data/data1.txt", 25)
|
|||
|
generate_random_numbers("/var/data/data2.txt", 30)
|
|||
|
generate_random_numbers("/var/data/data3.txt", 27)
|
|||
|
generate_random_numbers("/var/data/data4.txt", 12)
|
|||
|
generate_random_numbers("/var/data/data5.txt", 19)
|
|||
|
print("Генерация файлов завершена")
|
|||
|
|
|||
|
main()
|