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

运行实例