0

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

1 Answer 1

1

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

@M.baniasadi82 kindly accept/upvote if this was helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.