DAS_2024_1/karamushko_maxim_lab_2/service1/service.py
2024-12-05 17:25:26 +04:00

73 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import random
# Путь к каталогу для поиска файла с наибольшим кол-вом строк
path = "/var/data"
# Путь до файла с результатом
resultPath = "/var/result/data.txt"
def getMaxLines(directory):
result = None
maxLines = 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:
cnt = 0
for line in f:
cnt += 1
if cnt > maxLines:
maxLines = cnt
result = (filepath, cnt)
except (OSError, UnicodeDecodeError) as e:
print(f"Ошибка при обработке файла '{filepath}': {e}")
return result
def copyFile(first, second):
try:
with open(second, "wb") as second, open(first, "rb") as first:
while chunk := first.read(4096):
second.write(chunk)
print(f"Файл '{first}' успешно скопирован в '{second}'.")
except Exception as e:
print(f"Ошибка при копировании файла '{first}': {e}")
def generateRandomFiles(filename, count):
with open(filename, "w") as f:
for _ in range(count):
num = random.randint(0, 5000)
f.write(str(num) + "\n")
print(f"Случайные числа успешно записаны в '{filename}'.")
if __name__ == "__main__":
generateRandomFiles("/var/data/file1.txt", 6)
generateRandomFiles("/var/data/file2.txt", 9)
generateRandomFiles("/var/data/file3.txt", 19)
generateRandomFiles("/var/data/file4.txt", 11)
generateRandomFiles("/var/data/file5.txt", 15)
print("Генерация файлов завершена")
maxFile = getMaxLines(path)
if maxFile:
fPath, _ = maxFile
sPath = resultPath
copyFile(fPath, sPath)
else:
print("Не найдены файлы")