python - 为什么Python写入文件后不显示数据

标签 python

以下是我的代码

#!/usr/bin/python
from sys import argv
x, file_name = argv
print "planning to erase file %r. " , file_name
tgt=open(file_name,'r+')
print "deleting"
tgt.truncate()
print tgt.read()
print " no lines "
print "closed : ", tgt.closed
print "mode : ", tgt.mode
l1 = raw_input("line1 : ")
l2 = raw_input("line2 : ")
l3 = raw_input("line3 : ")
tgt.write(l1)
tgt.write('\n')
tgt.write(l2)
tgt.write('\n')
tgt.write(l3)
print "after writing"
print tgt.read()
print "Going to replace "
tgt.close()

最后读取的语句不显示数据。但该文件已更新为我输入的 3 行。 有什么帮助吗

最佳答案

您需要将光标移动到顶部再次读取该文件

tgt.seek(0)
print tgt.read()

关于python - 为什么Python写入文件后不显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31477344/

相关文章:

python - 如何在 Pandas 的时间序列图上绘制垂直线?

python - virtualenv 激活不起作用

python - 对元组中的相似元素求和

python - Matplotlib 和单元测试

python - 如何重新创建 Django 项目的数据库?

python - 如何从 Django 管理上传多个文件?

python twisted INotify 不阻塞 react 器

c# - 从用 C++ 编写的桌面应用程序过渡到基于 Web 的应用程序

python - 使用 groupby 的迭代长到宽 python 一行(或两行)

python - 具有颜色渐变的 3D 散点图,其中颜色取决于计数