0

I have a small file 5MB max size, having entries as below:

key_one = value_one
key_two = value_two
key_three = value_ three
.....

I need to iterate over each line and if the line matches certain condition, then I need to replace only the value part of the corresponding key in-place.

I have tried something like this:

def process_line():
    with open("input_path") as file:
        for each_line in file:
            if each_line.startswith('some_key'):
                new_value = "some_new_value"
                file.write(each_line.replace(each_line.split("=")[1],new_value))

This isn't updating the line in the file. So I am doing something wrong. How do I update just the individual line in the file?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    You have opened file in read mode and that might be reason for not updating. `r+` might be correct mode to open it if you want to do both read and write.. But I would suggest write to a new file and in the end remove old file and rename the new file to old filename. – skjoshi Jun 12 '18 at 16:54
  • Open the file in write mode. open("input_path", 'r+') – Joao Vitorino Jun 12 '18 at 16:54
  • https://stackoverflow.com/questions/14271216/beginner-python-reading-and-writing-to-the-same-file This answer might be able to help you understanding it better. – skjoshi Jun 12 '18 at 16:54
  • How will you handle the situation where the new value requires more bytes than the original value? – kindall Jun 12 '18 at 16:55
  • 1
    A true in-place updating is hard as it involves shifting contents which is much harder. It is also potentially a good bit slower. If really wishing to do it in-place (as opposed to write-replace or in-memory), use one path to generate the replacement offsets and another to work back through the file shifting data. I recommend using a new file - if the original file is "small" (ie. less than a GB), this can still be solved without a delete+copy by reading it all in at once with a truncate-open for the write. – user2864740 Jun 12 '18 at 17:00

0 Answers0