Pythonファイルwritelines()メソッド
例
追加する「a」を付けてファイルを開き、ファイルに追加するテキストのリストを追加します。
f = open("demofile3.txt", "a")
f.writelines(["See
you soon!", "Over and out."])
f.close()
#open
and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())
定義と使用法
このwritelines()
メソッドは、リストの項目をファイルに書き込みます。
テキストが挿入される場所は、ファイルモードとストリームの位置によって異なります。
"a"
:テキストは現在のファイルストリームの位置に挿入されます。デフォルトではファイルの最後に挿入されます。
"w"
:テキストが現在のファイルストリーム位置(デフォルトは0)に挿入される前に、ファイルは空になります。
構文
file.writelines(list)
パラメータ値
Parameter | Description |
---|---|
list | The list of texts or byte objects that will be inserted. |
その他の例
例
上記と同じ例ですが、リスト項目ごとに改行を挿入します。
f = open("demofile3.txt", "a")
f.writelines(["\nSee
you soon!", "\nOver and out."])
f.close()
#open
and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())