Je cherche à savoir comment faire de l'entrée et de la sortie de fichiers en Python. J'ai écrit le code suivant pour lire une liste de noms (un par ligne) d'un fichier vers un autre fichier tout en vérifiant un nom par rapport aux noms du fichier et en ajoutant du texte aux occurrences dans le fichier. Ce code fonctionne. Pourrait-on faire mieux ?
Je voulais utiliser le with open(...
pour les fichiers d'entrée et de sortie, mais je ne vois pas comment ils pourraient être dans le même bloc, ce qui signifie que je devrais stocker les noms dans un emplacement temporaire.
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')