我必须编写一个脚本,用来自input()
的特定变量替换.txt文件中的某些内容,然后它应该创建一个内容完全相同的新.txt,除了替换的内容。
我有一些条件:
将原始.txt中的行内容与特定字符串进行比较,如果相等,则将其替换为替换后的字符串,并将新字符串写入新的.txt文件中。
基本上,我必须进行几下复制\粘贴原始文件。但是,在测试阶段,整个配置将仅使用build_config()
函数中声明的 first 条件进行重写。而且,如果您运行我的脚本,您会发现LACP
条件根本不起作用,它仅以LACP
变量等于“ y”的情况下以任何方式写入内容。 “。
这是怎么回事?这是我的代码:
def build_config():
base_config = open("MES2428B.txt", 'r')
for line in base_config:
complete_config = open(location + ".txt", 'a')
complete_config.write(line)
line.replace("location", "location"+location)
complete_config.close()
base_config.close()
if lacp == "y" or "Y" or "Н" or "н" :
base_config = open("MES2428B_lacp.txt", 'r')
for line in base_config:
complete_config = open(location + ".txt", 'a')
complete_config.write(line)
base_config.close()
complete_config.close()
print("LOCATION:")
location = input()
print("VLAN:")
vlan = input()
print("Adress:")
ip = input()
print("LACP NEEDED? y/n")
lacp = input()
print("COM SPEED:")
COMspeed = input()
print("LOCATION: " + location + "\nVLAN: " + vlan + "\nIP: " + ip)
print("IS EVERYTHING RIGHT? y/n")
while True:
check = input()
if check == "y" or "Y" or "Н" or "н":
build_config()
print("Done, check it!")
input()
break
elif check == "n" or "N" or "т" or "Т":
print("What would you like to change? /n 1 - Локация /n 2 - VLAN /n 3 - IP /n 4 - COM Скорость /n 5 - nothing")
check = input()
if check == 1:
location = input()
elif check == 2:
vlan = input()
elif check == 3:
ip = input()
elif check == 4:
COMspeed = input()
elif check == 5:
print('Then why you press it!?')
build_config()
print("Done! Check it!")
input()
break
elif True:
print("Your input is garbage, try again")
'''
答案 0 :(得分:0)
欢迎来到。
您有if check == "y" or "Y" or "Н" or "н":
的地方,想要if check.lower() in ('y', 'h'):
答案 1 :(得分:0)
or
运算符采用两个布尔值并返回一个布尔值。
此表达式:
lacp == 'y' or 'Y'
将被评估如下:
lacp == 'y'
。'Y'
评估为布尔值并将其返回。任何非零,非空的值都将强制为true。因此您的表达式返回true。合并多个比较的正确一般方法是:
(lacp == 'y') or (lacp == 'Y')
这里不需要括号,但是我认为使用它们来明确评估顺序是个好习惯。
对于某些特定情况,例如您的情况,可能还会有其他合理的方法进行测试,如另一个答案所示。