I'm looking for how to do file input/output in Python. I wrote the following code to read a list of names (one per line) from a file and write them to another file. If the name read matches a name given by the user, I add a text to it before recording it. The code works, but how could I improve it?
I want to use the with open(...)
for the input and output files, but I don't see how to put them in the same block, which means I have to temporarily store the names somewhere else.
def filter(txt, oldfile, newfile):
'''\
Lee una lista de nombres desde un archivo línea por línea hacía un archivo de salida.
Si la línea comienza con un nombre en particular, insertar una cadena de texto
detrás del nombre antes de añadirlo a la línea del archivo de salida.
'''
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)] + ' - Realmente una gran persona!\n'
outfile.write(line)
outfile.close()
return # ¿Gano algo con agregar esto?
# Ingresar los nombres a revisar
text = input('Por favor, ingrese el nombre de una gran persona: ')
letsgo = filter(text, 'entrada.txt', 'salida.txt')
Python allows you to use multiple
open()
within awith
single , you just have to separate them with commas:Your complete code will look like this:
It's true, you gain nothing by putting an
return
explicit at the end of the function. You can use areturn
to perform an early exit, but you put it at the end, and the function will return the same, even if you don't put it. (Of course with functions that return a value you have to usereturn valor
to specify that value).We also save the
outfile.close()
, since files opened withwith open(
are automatically closed when exiting the statement block.In Python 2.5 and 2.6 you can't use multiples
open()
in awith
, but from Python 2.7 and 3.1 onwards you can.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