Advertisement
plarmi

workpython_13_4

Jun 24th, 2023
572
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. import os
  2.  
  3. input_file_path = 'исходный_файл.txt'
  4. output_file_path = 'новый_файл.txt'
  5. stars_line = '************'
  6.  
  7. # Проверяем существование исходного файла
  8. if not os.path.isfile(input_file_path):
  9.     print(f'Файл {input_file_path} не найден.')
  10.     exit()
  11.  
  12. # Читаем содержимое исходного файла
  13. with open(input_file_path, 'r') as input_file:
  14.     lines = input_file.readlines()
  15.  
  16. # Ищем последнюю строку без запятых
  17. last_line_without_comma = None
  18. for line in reversed(lines):
  19.     if ',' not in line:
  20.         last_line_without_comma = line
  21.         break
  22.  
  23. # Определяем индекс последней строки без запятых
  24. last_line_index = len(lines) if last_line_without_comma is None else lines.index(last_line_without_comma)
  25.  
  26. # Вставляем строку из звездочек после последней строки без запятых или в конец файла
  27. lines.insert(last_line_index + 1, stars_line + '\n')
  28.  
  29. # Записываем содержимое в новый файл
  30. with open(output_file_path, 'w') as output_file:
  31.     output_file.writelines(lines)
  32.  
  33. print(f'Файл {input_file_path} успешно обработан. Результат записан в {output_file_path}.')
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement