Работа с файлами и try-except

ТЕМА: Работа с файлами

Задание. Разработать программу для создания текстового файла и работы с ним. В программе реализовать обработку ошибок открытия файла с помощью конструкции try-except.

Разработать программу, которая: а) создает текстовый файл TF13_1 из символьных строк разной длины, слова в которых разделены пробелами и знаками препинания; б) читает содержимое файла TF13_1, находит слова, которые начинаются гласной буквой и записывает каждое в отдельную строку файла TF13_2; в) читает содержимое файла TF13_2 и печатает его по строкам.

Вот такой код у меня получился. Если кому-то не больно будет это разобрать, подскажите пожалуйста, как можно оптимизировать, уменьшить.

И как безболезненно в итоговом (втором файле со словами, что начинаются на гласные) убрать знаки препинания? Но это не оч важно.

def scheck(statusFileOk, inputFileName):
    if statusFileOk:
        print("The " + inputFileName + "file has been successfully processed", )
    else:
        print("Failed attempt to process a file ", inputFileName)


from successcheck import scheck

statusFileOk = False

while not statusFileOk:

    try:
        inputFileName = input("1.Enter the name of the file to create or edit: ")
        f = open(inputFileName, 'w')
    except IOError:
        print("File " + inputFileName + "could not be opened")
    else:
        statusFileOk = True
        f.write('uvnonasdkkasno' + "\n" + "aavavsdas121, spliter orobelom" + "\n" + "iegag, v konojy, 11")
        f.close()
    scheck(statusFileOk, inputFileName)

# Print the file TF13_1.txt content and close it
statusFileOk = False
while not statusFileOk:
    try:
        inputFileName = input("2.Enter name of input file: ")
        f = open(inputFileName, 'r')
    except IOError:
        print("File " + inputFileName + "could not be opened")
    else:
        statusFileOk = True
        print("Printing the file " + inputFileName + " content: ")
        for line in f:
            print(line)
        f.close()
    scheck(statusFileOk, inputFileName)

words = []
statusFileOk = False
while not statusFileOk:
    try:
        inputFileName = input("3.Enter name of input file: ")
        f = open(inputFileName, 'r')
    except IOError:
        print("File " + inputFileName + "could not be opened")
    else:
        statusFileOk = True
        for line in f:
            words += [w for w in line.split() if w.startswith(('a', 'e', 'i', 'o', 'u'))]
        f.close()
    scheck(statusFileOk, inputFileName)

# Write words (each from in line) to the file TF13_2.txt and close it
statusFileOk = False
while not statusFileOk:
    try:
        inputFileName = input("4.Enter name of input file: ")
        f2 = open(inputFileName, 'w')
    except IOError:
        print("File " + inputFileName + "could not be opened")
    else:
        statusFileOk = True
        for i in words:
            f2.write(i + "\n")
        f2.close()
    scheck(statusFileOk, inputFileName)

# Print the file TF13_2.txt content and close it

print("\nPrinting the file TF13_2.txt content: ")
statusFileOk = False
while not statusFileOk:
    try:
        inputFileName = input("5.Enter name of input file: ")
        f2 = open(inputFileName, 'r')
    except IOError:
        print("File " + inputFileName + "could not be opened")
    else:
        statusFileOk = True
        for line in f2:
            print(line)
        f2.close()
    scheck(statusFileOk, inputFileName)

Ответы (0 шт):