替换python fi中的行

2024-06-01 06:36:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个程序,给出一些整数值。我有一个文件,第一行有一个值。如何更改line的值(例如改为12)。这是我的密码,但是 这得到一个值,我想去第2行,把m加到第2行的那个数字上,但它不起作用。在

t=open('pash.txt', 'r')
g=[]
for i in range(3):
g.append(t.readline())
t.close()
g[o-1]=(int(g[o-1]))+m # o is the number of line in file
print(g[o-1])
t=open("pash.txt","w")
for i in range(3):
t.write(str(g[i]))
t.write('\n')
t.close()

Tags: 文件in程序txt密码forcloseline
1条回答
网友
1楼 · 发布于 2024-06-01 06:36:57

您可以open,使用readlines逐行读取文件,修改内容并重新write文件:

with open('pash.txt', 'r') as f:
    lines = f.readlines()

m = 5  # value you need to add to a line.
o = 2  # line number of the line to modify.
with open('pash.txt', 'w') as f:
    for x, line in enumerate(lines):
        if x == o:
            line = int(line) + m
        f.write(line) 

相关问题 更多 >