我想将我的变量的内容写入文件

时间:2016-05-30 18:31:54

标签: python string text-files

我已使用Python将curl命令的输出存储到字符串变量中。现在我想把它转移到一个文件。你能帮帮我吗?

我的字符串变量如下

>>> print result
health status index                      pri rep docs.count docs.deleted store.size pri.store.size 
yellow open   logstash-xxx-2016.05.18     5   1    1869483            0    477.9mb        477.9mb 
yellow open   logstash-xxx-2016.05.17     5   1     632263            0    158.8mb        158.8mb 
yellow open   logstash-xxx-2016.05.19     5   1    1534771            0    386.9mb        386.9mb
  1. 我想将此内容存储在一个文件中

  2. 仅从每一行中提取logstash-xxx-2016.05.18并仅将其写入另一个文件。

1 个答案:

答案 0 :(得分:0)

这会将结果写入名为' write_file.txt'以及匹配' logstash-xxx-xxxx.xx.xx'逐行到名为' write_logs.txt':

的文件
result = """health status index                      pri rep docs.count docs.deleted store.size pri.store.size 
yellow open   logstash-xxx-2016.05.18     5   1    1869483            0    477.9mb        477.9mb 
yellow open   logstash-xxx-2016.05.17     5   1     632263            0    158.8mb        158.8mb 
yellow open   logstash-xxx-2016.05.19     5   1    1534771            0    386.9mb        386.9mb"""

logs_index = [i for i in range(len(result)) if result.startswith('logstash', i)]

logs = [result[i:i + 23] for i in logs_index]

with open('write_file.txt', 'w') as f:
    f.write(result)

with open('write_logs.txt', 'a') as f:
    for l in logs:
        f.write(l + '\n')