我试图使用python在文件“example.txt”中添加数据。每次运行“Test.py”文件时,我都希望以增量顺序在文件中添加数据。
下面是我试过的代码
i = 0
for i in reversed(range(0,20,1)):
i = i+1
value = ("hash%s"%i)
index = 0
with open("Test.txt", "r") as f:
contents = f.readlines()
contents.insert(index, value)
with open("Test.txt", "w") as f:
contents = "".join(contents)
f.write(contents)
我的不满是:
hash1hash1hash1
预期产出:
On 1st run of code output should resemble: hash1
On 2nd run of code output should resemble: hash2
On 3rd run of code output should resemble: hash3