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)

參數值

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

更多實例

實例

與上例相同,但對每個列表項插入換行:

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

運行實例