Search code examples
pythonstringreadline

How to loop text file to create string of values


I'm somewhat new to python:
I'm trying to write a text file into a different format. Given a file of format:

[header]  
rho = 1.1742817531
mu = 1.71997e-05
q = 411385.1046712013 
...

I want:

[header]  
1.1742817531, 1.71997e-05, 411385.1046712013, ...

and be able to write successive lines below that.

Right now, I have the following:

inFile = open('test.txt', 'r')  
f = open('test.txt').readlines()  
firstLine = f.pop(0) #removes the first line  
D = ''  
for line in f:  
    D = line.strip('\n')  
    b=D.rfind('=')  
    c=D[b+2:]  
    line = inFile.readline()  

It returns only the last value, "3".
How do I get it to return a string (which will be saved to a new txt file) in the format I want?

Thanks in advance.


Solution

  • You could use a regex to recover only those lines you want. It depends on how specific you want to be but:

    import re
    regex = re.compile(r'^.+=')          #[edit]match any string up to '='
    result = []
    with open('test.txt') as fin:        #use with to auto-close the file when done
        for line in fin:
            line = line.rstrip('\n')
            if regex.search(line):
               #slice off last numbers in each line if match (for nums like 12)
               result.append(regex.split(line)[1]) 
    
    mystring = ','.join(result)         #merge list to string with ',' as separator
    

    Edit: Just noticed this can be done much more easily for the cases with no need for re module, just replace the if statement with this:

            if len(line.split('=')) == 2
                result.append(line.split('=')[1])