Search code examples
pythontext-parsing

How would update a line in a text file if it contains a certain string with user input in Python?


Currently I have a program that accepts a text file as a setting parameter. The format of the text file is like so:

text file format

What I would like to do in Python is to be able to parse the file. I want to read each line and check if it contains a specific string and if the line contains it, be able to append/update in place a user input text right into the end of that line.

For example, the "PRIMER_PRODUCT_SIZE_RANGE=" (highlighted) is found in the text file and I want to update it from "PRIMER_PRODUCT_SIZE_RANGE=100-300" to read for example "PRIMER_PRODUCT_SIZE_RANGE=500-1000". I want to be able to do this for several of the parameters (that I have chosen for my needs).

A few tools I've looked into would include fileinput module, doing a regular file open/write (which I can't do in place editing apparently), and a module I found called the in_place module.

Some preliminary code I have using the in_place module:

def SettingFileParser(filepath):
    with in_place.InPlaceText(filepath) as text_file:
        for line in text_file:
            if 'PRIMER_PRODUCT_SIZE_RANGE=' in line:
                text_file.write("idk what to put here")

I'm a noob programmer to preface so any help or guidance in the right direction would be appreciated.


Solution

  • You need to open the file for reading (default) and then you need to open a file for writing:

    def SettingFileParser(filepath):
        with open(filepath, 'r') as read_file:
            lines = read_file.readlines():
            with open(filepath, 'w') as write_file:
                for line in lines:
                    if line.startswith('PRIMER_PRODUCT_SIZE_RANGE='):
                        # keep the line the same except the part needing replacement
                        write_file.write(line.replace('100-300','500-1000'))
                    else:
                        # otherwise just write the line as is
                        write_file.write(line)