根据不同的用户输入替换字符串(模板配置)Python

2024-07-03 07:03:28 发布

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

我现在已经3天大了,所以请原谅我。你知道吗

我正在写一个程序,将采取配置模板内的变量,并有效地做查找和替换。唯一的区别是我希望它是为用户图形化的(稍后将提供),我希望它是动态的,以便变量可以在模板之间更改,即模板将从以下开始:

@hostname
@username
@password

下面的配置将在需要时包含@hostname等。你知道吗

hostname @hostname
login @username privilege 15 @password enc sha256

我的find和replace工作得很好,但是当程序在每个@variable之间循环时,每次都会复制我的模板。所以在本例中,我将在一个txt文件中堆叠3个模板。你知道吗

## OPEN TEMPLATE
with open("TestTemplate.txt", "rt") as fin:
    with open("out.txt", "w") as fout:
    ## PULLING VARIABLE NAMES
        for line in fin:
            if line.startswith("@"):
                trimmedLine = line.rstrip()
            ## USER ENTRY ie Please Enter @username: 
                entry = input("Please Enter " + trimmedLine + ": ")
                ## Open file again to start line loop from the top without affecting the above loop
                with open("TestTemplate.txt", "r+") as checkfin:
                    for line in checkfin:
                        if trimmedLine in line:
                            fout.write(line.replace(trimmedLine, entry))
                        else:
                        ## ENSURE ALL LINES UNAFFECTED ARE WRITTEN
                            fout.write(line)

正如您所看到的,当它写入所有行时,无论是否受影响,它都会对循环中的每个迭代执行此操作。我需要它只覆盖受影响的行,同时保留所有其他未受影响的行。我能让它们输出的唯一方法是用fout.write(line)输出每一行,但这意味着我得到了3倍的输出。你知道吗

我希望这是清楚的。你知道吗

谢谢


Tags: in程序txt模板aswithlineusername
2条回答

我不太清楚你想做什么,所以这也许是一个更合适的评论,但如果你能解释为什么你不做下面的,这将有助于给你建议如何做你想做的事。你知道吗

variable_names = #list variables here

variable_values={}
for variable_name in variable_names:
    variable_values[variable_name] = input("Please Enter " + variable_name + ": ")
with open("out.txt", "w") as fout:
    with open("TestTemplate.txt", "r+") as checkfin:
        for line in checkfin:
            for variable_name in variable_names:
                if variable_name in line:
                    line = line.replace(variable_name,variable_values[variable_name])
            fout.write(line)

IDLE的一个例子:

>>> fmtstr = "hostname {} login {} privilege 15 {} enc sha256"
>>> print (fmtstr.format("legitHost", "notahacker", "hunter2"))
hostname legitHost login notahacker privilege 15 hunter2 enc sha256

一旦您拥有了所有需要的数据(主机、用户、密码),就可以对字符串使用.format( )操作来替换所述字符串中的{}。如果字符串中有多个大括号对,则在方法中使用多个逗号分隔的参数,如上图所示,并按它们的显示顺序排列。你知道吗

相关问题 更多 >