写文件- write 方法
要写入文件,请使用 write 方法,该方法将字符串写入文件。
例如:
file = open("newfile.txt", "w")
file.write("This has been written to a file")
file.close()
file = open("newfile.txt", "r")
print(file.read())
file.close()
结果:
This has been written to a file
“w” 模式如果文件不存在,将创建一个文件。
写文件-“w” 模式
当以写入("w")模式打开文件时,文件的现有内容会被删除。
# -*- coding: UTF-8 -*-
file = open("newfile.txt", "r")
print("读取newfile.txt")
print(file.read())
print("===结束===")
file.close()
file = open("newfile.txt", "w")
file.write("写入一些新的内容")
file.close()
file = open("newfile.txt", "r")
print("再次读取newfile.txt")
print(file.read())
print("===结束===")
file.close()
自己试试。
写文件-返回
如果写入成功的话 write 方法返回写入文件的字节数。
msg = "Hello world!"
file = open("newfile.txt", "w")
amount_written = file.write(msg)
print(amount_written)
file.close()
结果:
12
网友评论