簡體   English   中英

替換python文件中的行

[英]replace line in python file

我想編寫一個給出一些整數值的程序。 我在第一行中有一個帶有值的文件。 如何更改line的值(例如更改為12)。 這是我的代碼,但是有一個值,我想轉到第2行,然后在第2行中將該數字加m,但這是行不通的。

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()

您可以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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM