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