简体   繁体   中英

replace line in python file

I want to write a program that gives some integer value. I have a file with a value in the first line. How can I change the value of line (for example to 12). This is my code, but this gets a value and I want to go to line 2 and addition m to that number in line 2 but it doesn't work.

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

You can open , read file line by line using readlines , modify content and re- write the file:

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM