轻松上手,快乐学习!

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 要插入的文本或字节对象。

更多实例

实例

与上面相同的实例,但在插入的文本之前插入换行符"\n"
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())
运行实例»