-1

I currently have a textfile that contains a master list that stores two list like this:

[Gerald D1 Completed D2 Pending]
[Adrian D1 Completed D2 Pending]

How can I edit Adrian's D2 Pending to D2 Completed and store it back into a textfile?

  • Does this answer your question? [Search and replace a line in a file in Python](https://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python) –  Aug 29 '21 at 09:06
  • You'll have to tell us something about the format of your data. There are lots of approaches that will work for this _specific_ instance of the problem, but probably not any other ones. – Adam Smith Aug 29 '21 at 09:06
  • Personally I would use sed. `sed -i '/Adrian/ s/Pending/Completed/' somefile.txt` – Adam Smith Aug 29 '21 at 09:07
  • How would you programmatically identify the line that you want to change? Also, the notion of a text file containing a list is rather ambiguous. Can you explain that? –  Aug 29 '21 at 09:40

1 Answers1

0

Here's a very simplistic solution for this specific case:-

with open('foo.txt', 'r+') as dfile:
    lines = dfile.readlines()
    dfile.seek(0)
    dfile.truncate()
    for line in lines:
        ls = line.split()
        if ls[0] == '[Adrian' and ls[4] != 'Completed]':
            ls[4] = 'Completed]\n'
            dfile.write(' '.join(ls))
        else:
            dfile.write(line)