Py学习  »  Python

有什么方法可以使用python以增量顺序在文件中添加数据吗

Voldermort 007 • 4 年前 • 1957 次点击  

我试图使用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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130128
文章 [ 1 ]  |  最新文章 4 年前
Armali
Reply   •   1 楼
Armali    5 年前

这会产生(几乎)你的 预期产量 分三次运行:

with open("Test.txt", "a+") as f:
    f.seek(0)
    value = len(f.readlines())+1
    f.write(f"On {value}. run of code output should resemble: hash{value}\n")