【问题标题】:How to loop text file to create string of values如何循环文本文件以创建值字符串
【发布时间】:2019-11-20 01:50:39
【问题描述】:

我对 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 文件中)?

提前致谢。

【问题讨论】:

  • 您想要输出文件中每一行的数字吗?

标签: python string readline


【解决方案1】:

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

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

【讨论】:

  • 逻辑很简洁,但最终实现起来要困难得多,因为我为了发布而简化了输入。真正的输入文件看起来更像这样,其中变量名称不一致,并且变量值的位数不断变化:rho = 1.1742817531 mu = 1.71997e-05 q = 411385.1046712013
  • 是的,用于解析的正则表达式有点棘手。如果你在文件的每一行都有'some quantity = num'并且想要提取所有的nums,上面的正则表达式可以简化为re.compile(r'^.+='),效果相同。
  • 我看到指向最后一行的“对象不可下标”错误。我不熟悉这个错误。 :|
  • 我的错字很愚蠢。我应该在join 中的函数调用中使用括号现在应该可以工作了。使用 mystring = mystring.lstrip() 删除任何前导空格。
  • 当然,很高兴为您提供帮助。
【解决方案2】:

尝试使用:

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

【讨论】:

  • 关闭,但这输出“333”,而我正在寻找“1 2 3”。
  • @BrendanMcBreen 已编辑,立即尝试
  • 我们更接近了。我们现在有一列值,但我需要在一行上用空格或制表符分隔它们。我还需要能够识别我正在写入哪一行,所以下次运行脚本时我不会覆盖这些数据。
  • @BrendanMcBreen 编辑重试
  • 嗯。这只是 test2.txt 文件的“双空格”。我需要将结果字符串放在一行中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 2017-06-19
相关资源
最近更新 更多