私はPythonでファイルの入出力を行う方法を見ています。私は、ファイル内の名前に対して名前をチェックし、ファイル内の出現箇所にテキストを追加しながら、ファイルから別のファイルに名前のリスト(1行に1つ)を読み込む次のコードを書いた。コードは機能します。それはもっとうまくいくだろうか?open with文を使ってファイルを開く方法
入力ファイルと出力ファイルの両方にwith 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')
?あなたはこれによって何を意味するのか説明できますか? 'フィルタ()'である[組み込み関数](https://docs.python.org/2/library/functions.html#filter)ので、あなたはおそらく、あなたの関数に別の名前を選択する必要があることを –
注意。 – Tom
@Tomは名前空間内の関数が組み込み関数をオーバーライドしていますか? – UpTide