Ask coding questions

← Back to all posts
Changing a string from a specific line in text file
ZestyLad (11)

Can anyone tell me how to change the value of loan of a member here in my program? Like let's say I want to change Anne's loan value from 750 to 1000, how can I change only hers and keep the rest? i tried doing the readlines() method but I still cant get to change it, tried researching about it on stackoverflow too but still cant get something out of it. Any help would be appreciated!

Answered by c4syner (77) [earned 5 cycles]
View Answer
Commentshotnewtop
c4syner (77)
with open('abc.txt','w') as f:
    f.write("Members\t\tLoans"+"\nMark\t\t500"+"\nSteve\t\t1000"+'\nAnne\t750'+'\nAlpha\t520')

a=input("Enter name: ")
b=input("Enter new loan: ")
index = 0
with open('abc.txt','rt') as f:
    lines = f.readlines() #readlines is crucial here
    for i in range(len(lines)):#Find index of line where user is 
      if a in lines[i]:
        index = i 
    #now have index replace value
    mainStr = lines[index]
    originalStr = mainStr #preserve original value
    curNum = int(''.join(filter(str.isdigit, mainStr))) #find current loan
    mainStr = mainStr.replace(str(curNum), str(b)) #change value of loan
    for i in range(len(lines)): #replace value of original loan
      if originalStr in lines[i]:
        lines[i] = mainStr
    lines = "".join(lines) #make it into a big string like before
    print(lines)

with open('abc.txt','w') as f:
    f.write(lines)

This should work pretty good, supports the same file export that you had in your original code and can support more people being added.

please upvote if this helped

ZestyLad (11)

@c4syner Its giving me an error with line 15 cause of integer conversion error.

c4syner (77)

@ZestyLad just make sure you're putting the literal name of the individual. Instead of putting mark put Mark for example.

ZestyLad (11)

@c4syner Oh yeah, how dumb of me, its working now, thanks!

Codemonkey51 (923)

What you can do is open the file in read mode then set a variable named contents = {filevar}.read() then make any changes to contents next do {filevar}.close() open the file in write mode then {filevar}.write(contents) {filevar}.close()

Codemonkey51 (923)

{filevar} as in the variables you opened the file as

Codemonkey51 (923)

Your welcome sorry if it was a bit hard to understand @ZestyLad

ZestyLad (11)

@Codemonkey51 No worries! I get the idea anyway.