用‘w+’格式写文件之后,在进行读操作结果没有输出,也没有报错

代码如下
from sys import argv
script, filename = argv
print("we are going to erase %r"%(filename))
print("if you don't want that, hit ^c")
print("if you do want that, hit return")

input("?")

print("opening the file...")
target = open(filename, 'w+')

print("truncating the file")
target.truncate()

print("now i am going to ask you for three lines")

line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

print("i am going to write these to the file")

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print("now this is your new file")
print(target.read())
#不知道为什么没有打出来,也没报错

print("and finally, we close it")
target.close()

图片说明

你的文件名和文件路径是什么,用绝对路径试试看。检查下对应目录的权限,或者用管理员模式运行

默认情况下,输出文件总是缓冲的,这意味着写入的文本可能不会立即写入自动从内存转到硬盘——关闭一个文件或者运行flush()方法迫使缓存的数据进入硬盘。

……

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

target.close()

target = open(filename)
print("now this is your new file")
print(target.read())

print("and finally, we close it")
target.close()

输出:

 we are going to erase 'test.txt'
if you don't want that, hit ^c
if you do want that, hit return
?
opening the file...
truncating the file
now i am going to ask you for three lines
line 1: a
line 2: aa
line 3: aaa
i am going to write these to the file
now this is your new file
a
aa
aaa

and finally, we close it

貌似 w+ 在打开一个存在的文件的时候,会一开始就删除其中的内容。所以这时候read了会是空的