在使用python搜索文件中的字符串后,如何打印此内容?

2024-05-16 03:37:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以搜索这些值,但在执行此文件log.txt时,我遇到了一个难题,即如何以这种格式打印

Dlog = 0
MeanDlog = 102
i_min = 22 


Dlog = 10
MeanDlog = 10
i_min = 20

我有一个file.txt,它多次重复这些行,但是它的值改变了,我需要像这样保存这些行

在执行该文件后,以这样的方式打印

Dlog = {0, 10} 
MeanDlog = {102,10}
i_min = {22,20}

Tags: 文件txtlog格式方式mindlogfile
1条回答
网友
1楼 · 发布于 2024-05-16 03:37:42

这将对您有用:

variables = dict() #Create a dictionary to store the split lines

with open("input.txt") as i_file: #Open the file
    for line in i_file:
        if line == "\n" or line.find("=") == -1: #Skip blank lines and lines with no equals sign
            continue
        name, value = line.strip("\n").split(" = ") #Split lines into two parts based on the "=" sign

        if name not in variables:
            variables[name] = list()

        variables[name].append(int(value))

with open("output.txt", "w") as o_file: #Can be changed to whatever file you want to write to
    for item in variables:
        temp = str(variables[item])
        temp = temp.replace("[","{").replace("]","}").replace(" ", "")
        o_file.write(item + " = " + temp +"\n")

相关问题 更多 >