以下是我的代码
#!/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/