2

How would I update a file with out rewriting it or anything but search for the value that I want to update so lets say in the file I have this data:

George|40|19|80|yes
Bob|19|20|01|no
James|30|19|90|yes

But I want to search for Bob without overwriting the whole file and change bob to

Bob|23|20|01|yes

But still have the values in it but updated:

George|40|19|80|yes
Bob|23|20|01|yes
James|30|19|90|yes

Is this possible to do this without using the write module in python?
If this isn't possible doing this then sorry for wasting your time

Bond 007
  • 210
  • 2
  • 12

3 Answers3

3

If you are just using text files, then no, you need to write the whole file back.

This is why there are loads of other file formats, and things like SQL exist.

Take a look at this answer for a hint on how to do the single-line editing with a full-file rewrite.

Luke Storry
  • 6,032
  • 1
  • 9
  • 22
1

You can find the index of "Bob", then get your cursor there using seek() function, finally overwrite that line.

f = open("test.txt", "r+")
text = f.read()
cursor_index = text.find("Bob")
f.seek(cursor_index)
f.write("Bob|23|20|01|yes\n")
f.close()
enesdemirag
  • 325
  • 1
  • 10
0

I have done this but thanks for the suggestions

with open('accounts_project.txt','r+') as f:
    global newline
    newline=[]
    for line in f.readlines():
        newline.append(line.replace(backup, lockaccount))
    newline= "".join(newline)
with open('accounts_project.txt','w+') as f:
    for line in newline:
        f.writelines(line)

This works as well

Bond 007
  • 210
  • 2
  • 12