0

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!

user2068783
  • 1
  • 1
  • 4

1 Answers1

0

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.

Korem
  • 11,383
  • 7
  • 55
  • 72
  • Hm, looks like I'm having some problems with this method, and I think it's based on having spaces within 'variable7 = 34' in the .txt file. The only way I've managed to get 'None' returned is to write the second line as follows: sp = l.split(' = ') With that, 'None' is returned for 'variable7 = ' and variable7 ='. If in fact an integer is defined, however, so, 'variable7 =23' (with no space) 'None' is still returned, but if it's written as, 'variable7 = 23', then the '23' is recorded. I'd like to eliminate this sensitivity to spaces, if possible. Thanks again. – user2068783 Jun 19 '14 at 09:23
  • Thank you so much. I really appreciate all the help. – user2068783 Jun 19 '14 at 10:59