Search code examples
pythonbashgetlinelinecache

Extracting specific variables of a line with linecache


I'm currently using the python linecache module to grab specific lines from a given text document and create a new file with said line. For example, part of the code looks like:

cs = linecache.getline('variables.txt', 7)
cs_1 = open("lo_cs", "w")
cs_1.write(str(cs))
cs_1.close()

The problem is that within variables.txt, line 7 is given by:

variable7 = 3423

for instance. I want the new file, lo_cs, however, to contain only the actual value '3423' and not the entire line of text. Further, I want to insert the whole 'getline' command into an if loop so that if variable7 is left blank, another action is taken. Is there a way to use linecache to check the space following 'variable7 = ' to see if there is anything entered there, and if so, to grab only that particular value or string?

I know (but don't really understand) that bash scripts seem to use '$' as sort of a placeholder for inserting or calling a given file. I think I need to implement something similar to that...

I thought about having instructions in the text file indicating that the value should be specified in the line below -- to avoid selecting out only segments of a line -- but that allows for one to accidentally enter in superfluous breaks, which would mess up all subsequent 'getline' commands, in terms of which line needs to be selected.

Any help in the right direction would be greatly appreciated!


Solution

  • You can use the following method to wrap the functionality you need:

    def parseline(l):
        sp = l.split('=')
        return sp[0], int(sp[1]) if len(sp) > 1 else None
    

    or if you don't need the variable name:

    def parseline(l):
        sp = l.split('=')
        return int(sp[1]) if len(sp) > 1 and sp[1].strip() != '' else None
    

    and then use:

    csval = parseline(linecache.getline('variables.txt', 7))
    

    You can later place conditions on csval to see if it's None, and if it is, take another action.