如何循环文本文件以创建值字符串

How to loop text file to create string of values

我对 python 有点陌生:
我正在尝试将文本文件写入不同的格式。给定格式的文件:

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

我要:

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

并能够在其下写下连续的行。

现在,我有以下内容:

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()  

它 return 只是最后一个值,“3”。
如何将它变成 return 我想要的格式的字符串(将保存到新的 txt 文件)?

提前致谢。

尝试使用:

with open('test.txt', 'r') as f, open('test2.txt', 'w') as f2:
    lines = f.readlines()
    for line in lines[1:]:  
        b=line.rfind('=')  
        c=line[b+2:]  
        f2.write(c + '\n')

您可以使用正则表达式来仅恢复您想要的那些行。这取决于您想要的具体程度,但是:

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

编辑:刚刚注意到对于不需要 re 模块的情况,这可以更容易地完成,只需将 if 语句替换为:

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