Как открыть файл с помощью оператора open with

Я смотрю, как выполнять ввод и вывод файлов в Python. Я написал следующий код для чтения списка имен (по одному в каждой строке) из файла в другой файл, при этом сравнивая имя с именами в файле и добавляя текст к вхождениям в файле. Код работает. Можно ли сделать лучше?

Я хотел бы использовать с оператором open (... как для входных, так и для выходных файлов, но не вижу, как они могут быть в одном блоке, то есть мне нужно сохранить имена во временном расположении.

def filter(txt, oldfile, newfile):
    '''\
    Read a list of names from a file line by line into an output file.
    If a line begins with a particular name, insert a string of text
    after the name before appending the line to the output file.
    '''

    outfile = open(newfile, 'w')
    with open(oldfile, 'r', encoding='utf-8') as infile:
        for line in infile:
            if line.startswith(txt):
                line = line[0:len(txt)] + ' - Truly a great person!\n'
            outfile.write(line)

    outfile.close()
    return # Do I gain anything by including this?

# input the name you want to check against
text = input('Please enter the name of a great person: ')    
letsgo = filter(text,'Spanish', 'Spanish2')
184
задан marcospereira 24 January 2017 в 04:57
поделиться