如何在声明L =打开(...)然后W =打开(...,' w')后保持文件完好无损

时间:2018-02-04 23:01:51

标签: python file

我的代码 j.py 和文本文件 j.txt

#I have something written in j.txt
L=open('j.txt') #I define this variable because will use it multiple times later
W=open('j.txt','w') #I define this variable because will use it multiple times later
for line in L:
    print(line)
L.close()
W.write('abc')
W.close()

但什么都不打印。因为看起来仅仅定义W=open('j.txt','w')的行为将立即触发行动' w'重写文件 j.txt

有办法解决吗?我的意思是,在命令像W.write('anything')

这样的东西时,只能用W模式有效地写入

1 个答案:

答案 0 :(得分:0)

我认为你应该使用'r +'模式。 'r +'是特殊的读写模式,用于处理文件时的两种操作。 尝试这样的事情:

with open("file.txt", "r+") as f:
   d = f.read()
   print d
   f.seek(0)
   f.write("some data")
   f.truncate()