python刚写入的文件无法读取的问题

在尝试写入文件后立即读取时发现文件内容为空。问题出在写入文件后未关闭文件,因此写入的数据未被保存。解决方案是确保在读取前关闭文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用此代码进行写文件然后读出来的时候,读出的文件为空

from sys import argv 
script, filename = argv 

print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.") 

input("?")

print("Opening the file...")
target = open(filename, 'r+') 
print("Truncating the file. Goodbye!")
target.truncate() 

print("I'm going to write these to the file.") 

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

print("Target's content is:")
print(target.read())
print("And finally, we close it.")
target.close()

输出:

C:\Users\Starwaves\Desktop>python pt.py pt_smp.txt
We're going to erase pt_smp.txt.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
I'm going to write these to the file.
Target's content is:

And finally, we close it.

经过排查之后,发现是写入文件之后没有用target.close()关闭文件,所以写入内容并没有保存,提前先target.close()了再读取就好了

from sys import argv 
script, filename = argv 

print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.") 

input("?")
print("Opening the file...")
target = open(filename, 'r+') 
print("Truncating the file. Goodbye!")
target.truncate() 

print("I'm going to write these to the file.") 

target.write("line1")
target.write("\n")
target.write("line2")
target.write("\n")
target.write("line3")
target.close()
target = open(filename, 'r+') 
print("Target's content is:")
print(target.read())
print("And finally, we close it.")
target.close()

输出:

C:\Users\Starwaves\Desktop>python pt.py pt_smp.txt
We're going to erase pt_smp.txt.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
I'm going to write these to the file.
Target's content is:
line1
line2
line3
And finally, we close it.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值