Правильная работа с файлами - Python

Узнай цену своей работы

Формулировка задачи:

Я написал небольшой скрипт, который разбирает текстовый файл со строками (разделенными табуляциями) в виде html, проводит небольшую их обработку и генерирует html, который собственно и нужен на выходе. Также приходится открывать много файлов, с исходными данными на чтение, и 3 на запись (один - html, второй - просто текстовый, третий - результаты обработки (что-то врдое лога, только для других целей)). В результате получилось очень много try-except-else-finally блоков, которые вложены друг в друга. На мой взгляд это выглядит немного громоздко и некрасиво! К тому же эти вложенные блоки сдвигают код вправо, так что строки даже не помещались в IDLE, что не очень удобно с точки зрения разработки. Есть ли какой-нибудь способ, как можно от этого избавиться от вложенных try-except-else-finally блоков? Там где есть возможность, я просто читал файлы в словарь в памяти, и такие try-except-else-finally блоки расположены в колонку, что уже выглядит получше, но тоже не фонтан. Я знаю про конструкцию with. Но в моем коде происходит анализ всех ошибок открытия файла через try-except-else-finally блок, а with не позволяет обработать исключения (он просто файл закроет в случае ошибок обработки и все, а мне нужно еще сделать некоторые действия перед этим (вывод на экран для визуального контроля выполнения скрипта)). Да, опыта написания на Питоне у меня большого нет, хотя я прочитал много документации по этому языку. Поэтому любые замечания по коду приветствуются.
Листинг программы
  1. # -*- coding: utf-8 -*-
  2. import re
  3. import codecs
  4. import sys
  5. from pprint import pprint
  6. f_exclusions_name = 'words_posted2.txt' #file with words to exclude
  7. f_exclusions_name2 = 'words_I_want_to_exclude_3.txt' #file with words I want to exclude
  8. file_in_name = 'anki_out3.txt' #input file name
  9. file_out_htm_name = 'out3.htm' #output html file name
  10. file_out_txt_name = 'out3.txt'#output txt file name
  11. word_to_exclude_next_time_file_name = 'words_posted3.txt'
  12. html_head = u'''
  13. <html>
  14. <head>
  15. <title>Words list 3</title>
  16. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  17. </head>
  18. <body>
  19. '''
  20.  
  21. to_exclude_dict = {} #dict of words to exclude
  22. excluded_words_dict = {} #dict of excluded words
  23. word_to_exclude_next_time_dict = {}
  24. #Forming to_exclude_dict dictionary
  25. try:
  26. f_exclusions = codecs.open(f_exclusions_name,encoding='UTF-8')
  27. except IOError:
  28. print('Can\'t open the file {0}'.format(f_exclusions_name))
  29. sys.exit(1)
  30. else:
  31. for line in f_exclusions:
  32. line = line.rstrip('\n\r ')
  33. to_exclude_dict[line] = True
  34. finally:
  35. f_exclusions.close()
  36. try:
  37. f_exclusions = codecs.open(f_exclusions_name2,encoding='UTF-8')
  38. except IOError:
  39. print('Can\'t open the file {0}'.format(f_exclusions_name2))
  40. else:
  41. for line in f_exclusions:
  42. line = line.rstrip('\n\r ')
  43. to_exclude_dict[line] = True
  44. finally:
  45. f_exclusions.close()
  46.  
  47. try:
  48. f_in = codecs.open(file_in_name,encoding='UTF-8')
  49. except IOError:
  50. print('Can\'t open the file {0}'.format(file_in_name))
  51. else:
  52. try:
  53. f_out_htm = codecs.open(file_out_htm_name,mode='w',encoding='UTF-8')
  54. except IOError:
  55. print('Can\'t open the file {0}'.format(file_out_htm_name))
  56. else:
  57. try:
  58. f_out_txt = codecs.open(file_out_txt_name,mode='w',encoding='UTF-8')
  59. except IOError:
  60. print('Can\'t open the file {0}'.format(file_out_txt_name))
  61. else:
  62. try:
  63. word_to_exclude_next_time_file = codecs.open(word_to_exclude_next_time_file_name,mode='w',encoding='UTF-8')
  64. except IOError:
  65. print('Can\'t open the file {0}'.format(word_to_exclude_next_time_file_name))
  66. else:
  67. f_out_htm.write(html_head)
  68. f_out_htm.write(u'<table border="1" cellspacing ="0" cellpadding ="3" width="100%">')
  69. f_out_htm.write(u'<tr>')
  70. f_out_htm.write(''.join((u'<th>',u'№',u'</th><th>',u'Слово',u'</th><th>',u'Значение',u'</th>')))
  71. f_out_htm.write(u'</tr>\n')
  72. pattern1 = re.compile(r'\t')
  73. pattern2 = re.compile(r'</?span.*?>|^ +| +$|\n')
  74. pattern3 = re.compile(r'<img src="(.*?)" />')
  75. i = 0
  76. for j, line in enumerate(f_in):
  77. #print(u'Line in: {0}\n'.format(line))
  78. strings = pattern1.split(line)
  79. word = pattern2.sub('',strings[0]) #striped of html-garbage string[0]
  80. word_to_exclude_next_time_file.write(word+u'\n')
  81. #print(u'Word: {0}'.format(word))
  82.  
  83. #Adding the found values in the to_exclude_dict into the excluded_words_dict
  84. if word in to_exclude_dict:
  85. #print(u'Excluded: {0}\n'.format(word))
  86. excluded_words_dict[word] = True
  87. continue #no parsing for the data which is in the to_exclude_dict
  88. f_out_txt.write(word+'\n')
  89. f_out_htm.write(u'<tr>')
  90. i += 1 #number of the table row
  91. line = u'<td>'+'{0}'.format(i)+'</td><td>'+strings[0]+u'</td>'+u'<td>'
  92. definition = strings[2]
  93. image = pattern3.search(definition)
  94. if image:
  95. #print(u'Image detected: {0}'.format(image.group(0)))
  96. #adding my public DropBox address
  97. definition = pattern3.sub(u'<img style="border:5px solid white" src="http://dl.dropbox.com/u/7801003/Different.media/\g<1>" width="50%" />',strings[2])
  98. #print(u'Replaced definition string: {0}\n'.format(definition))
  99. if definition: #there may be no definition
  100. line += definition
  101. else:
  102. line += '&nbsp' #otherwise the cells are empty and have no borders in the html
  103. #Adding examples
  104. if strings[3]: #there may be no examples
  105. line += u'<p><span style="color:blue; font-style:italic;">'+strings[3]+u'</span></p>'
  106. line += u'</td>'
  107. f_out_htm.write(line)
  108. f_out_htm.write(u'</tr>\n')
  109. f_out_htm.write(u'</table>')
  110. finally:
  111. word_to_exclude_next_time_file.close()
  112. finally:
  113. f_out_txt.close()
  114. finally:
  115. f_out_htm.close()
  116. finally:
  117. f_in.close()
  118. #the set of words which haven't been excluded for some reason
  119. not_excluded = set(to_exclude_dict) - set(excluded_words_dict)
  120. print(u'\nWords that haven\'t been excluded:'.format(word))
  121. for word in not_excluded:
  122. print(u'{0}'.format(word))
  123. print('\nParsing completed')
Спасибо всем откликнувшимся

Решение задачи: «Правильная работа с файлами»

textual
Листинг программы
  1. file open(file_in_name, file_object_name='file_in'):
  2.     file open(file_out_html_name, file_object_name='file_out_html'):
  3.        ....

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

9   голосов , оценка 4.111 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут