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)

參數值

參數 描述
byte 將要插入的文本或字節對象。

更多實例

實例

與上例相同,但在插入的文本前面插入換行:

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())

運行實例