RaspiBerry Blog

CnLiutiezhu is here!

python 向文件写入内容

| 暂无评论

如果忘记fo.close()文件内容永远是空的,只有执行了close文件才开始写入!@@……@@czliutz
# 打开一个文件
fo = open("foo.txt", "w")
fo.write( "www.runoob.com!\nVery good site!\n")

# 关闭打开的文件
fo.close()

因此,Python引入了with语句来自动帮我们调用close()方法:

with open('/path/to/file', 'r') as f:
    print(f.read())

发表回复

*为必填字段!