Добрый вечер!
Несколько недель назад, на своей работе, я столкнулся с несколькими не очень обязательными, но интересными задачами по автоматизации. Одна задача больше относится к теме парсинга, которую сегодня я не готов трогать, а вторая представляет собой работу с файлами, чтение, выделение нужных данных и вывод нужной информации из них в отдельный файл. Об этом я и хочу написать.
Опыт программирования у меня нулевой, но тем не менее свой код я всё же дальше представлю и к конструктивной критике вполне готов. Для решения своей задачи я выбрал язык Python, так как он является одним из популярных и понятных языков, а ещё потому, что есть пара человек, у которых я мог спросить совета. В ходе написания кода приходилось бороться с некоторыми возникающими ошибками, решение которых для меня не всегда было очевидным, но тем не менее я его находил.
После устранения ошибок я решил рассказать коллеге о том, как решил его задачу и какие ошибки возникали. Он же подсказал мне, что в Python есть конструкция try… except, которая позволяет не обращать внимания на ошибки, если они не мешают выполнению кода. Я почитал про эти методы в интернете, убрал часть кода, решавшую возникающие ошибки и заменил исполнение его вышеуказанной конструкцией, поместив в except две ошибки, всё работает как надо и вроде бы в чём проблема, работает и работает, че бубнить то. Однако меня волнует вопрос того, что конструкция позволяет простить разработчику ошибки и не думать об их решении, по этому поводу и хотелось бы узнать мнение, также приложу весь код, чтобы можно было наглядно увидеть разницу.
import os import re import datetime output_file = "output_{}.txt".format(datetime.datetime.today().strftime("%d-%m-%y_%H-%M-%S")) old_output_file = "old_output_{}.txt".format(datetime.datetime.today().strftime("%d-%m-%y_%H-%M-%S")) fnames = [_ for _ in os.listdir(os.getcwd()) if _.endswith(r".txt")] filenames = [] for filename in fnames: if 'output' not in filename: filenames.append( filename ) old_files = [_ for _ in os.listdir(os.getcwd()) if _.startswith(r"output")] for file in old_files: if 'output' in file: old_file = 'old_' + file os.rename(file, old_file) def read_file(filename): with open(filename) as input_file: text = input_file.readlines()[2:] return text def parse_user_datafile_simintech(): results = [] degree = 0 text = read_file(filename) for line in text: line = re.sub("[a-z = \t \n]", "", line) if '-' not in line[0]: line = '+' + line if degree == 0: line = re.sub("[A-D F-Z a-z = \n ]", "", line) results.append( '=' + line ) if degree != 0: line = re.sub("[A-D F-Z a-z = \n ]", "", line) results.append( line + '*x^' + str(degree) ) degree += 1 return results def parse_user_datafile_excel(): results = [] degree = 0 text = read_file(filename) for line in text: line = re.sub("[a-z = \t \n]", "", line) if '-' not in line[0]: line = '+' + line if degree == 0: line = re.sub("[A-D F-Z a-z = \n ]", "", line) line = re.sub("[.]", ",", line) results.append( '=' + line ) if degree != 0: line = re.sub("[A-D F-Z a-z = \n ]", "", line) line = re.sub("[.]", ",", line) results.append( line + '*A2^' + str(degree) ) degree += 1 return results def write_data_to_output(): output_file = "output_{}.txt".format(datetime.datetime.today().strftime("%d-%m-%y_%H-%M-%S")) with open(output_file, 'a+') as output_file: output_file.writelines(filename) output_file.writelines('\n') output_file.writelines(parse_user_datafile_simintech()) output_file.writelines('\n \n') output_file.writelines(parse_user_datafile_excel()) output_file.writelines('\n \n \n') return output_file for filename in filenames: read_file(filename) parse_user_datafile_simintech() parse_user_datafile_excel() write_data_to_output()
import os import re import datetime output_file = "output_{}.txt".format(datetime.datetime.today().strftime("%d-%m-%y_%H-%M-%S")) filenames = [_ for _ in os.listdir(os.getcwd()) if _.endswith(r".txt")] old_files = [_ for _ in os.listdir(os.getcwd()) if _.startswith(r"output")] for file in old_files: if 'output' in file: old_file = 'old_' + file os.rename(file, old_file) def read_file(filename): with open(filename) as input_file: text = input_file.readlines()[2:] return text def parse_user_datafile_simintech(): results = [] degree = 0 text = read_file(filename) for line in text: line = re.sub("[a-z = \t \n]", "", line) if '-' not in line[0]: line = '+' + line if degree == 0: line = re.sub("[A-D F-Z a-z = \n ]", "", line) results.append( '=' + line ) if degree != 0: line = re.sub("[A-D F-Z a-z = \n ]", "", line) results.append( line + '*x^' + str(degree) ) degree += 1 return results def parse_user_datafile_excel(): results = [] degree = 0 text = read_file(filename) for line in text: line = re.sub("[a-z = \t \n]", "", line) if '-' not in line[0]: line = '+' + line if degree == 0: line = re.sub("[A-D F-Z a-z = \n ]", "", line) line = re.sub("[.]", ",", line) results.append( '=' + line ) if degree != 0: line = re.sub("[A-D F-Z a-z = \n ]", "", line) line = re.sub("[.]", ",", line) results.append( line + '*A2^' + str(degree) ) degree += 1 return results def write_data_to_output(output_file): with open(output_file, 'a+') as output_file: output_file.writelines(filename) output_file.writelines('\n') output_file.writelines(parse_user_datafile_simintech()) output_file.writelines('\n \n') output_file.writelines(parse_user_datafile_excel()) output_file.writelines('\n \n \n') return output_file try: for filename in filenames: read_file(filename) parse_user_datafile_simintech() parse_user_datafile_excel() write_data_to_output(output_file) except FileNotFoundError: print('The End!') except IndexError: print('The End!')
ссылка на оригинал статьи https://habr.com/ru/post/709094/
Добавить комментарий