Python permite poner múltiples open()
declaraciones en una sola with
. Sepárelos por comas. Su código sería entonces:
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.
'''
with open(newfile, 'w') as outfile, 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)
# input the name you want to check against
text = input('Please enter the name of a great person: ')
letsgo = filter(text,'Spanish', 'Spanish2')
Y no, no ganas nada poniendo un explícito return
al final de su función. Puedes usar return
para salir temprano, pero lo tenía al final, y la función saldrá sin él. (Por supuesto, con funciones que devuelven un valor, se usa el return
para especificar el valor a devolver.)
Usando múltiples open()
artículos con with
no era compatible con Python 2.5 cuando el with
se introdujo la declaración, o en Python 2.6, pero es compatible con Python 2.7 y Python 3.1 o más reciente.
http://docs.python.org/reference/compound_stmts.html#the-with-statement
http://docs.python.org/release/3.1/reference/compound_stmts.html#the-with-statement
Si está escribiendo código que debe ejecutarse en Python 2.5, 2.6 o 3.0, anide el with
declaraciones como las otras respuestas sugirieron o usan contextlib.nested
.