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

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

它仅返回最后一个值“ 3”。
如何获取它以我想要的格式返回字符串(将保存到新的txt文件中)?

谢谢。

tecie88986 回答:如何循环文本文件以创建值字符串

尝试使用:

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])
本文链接:https://www.f2er.com/3069250.html

大家都在问