将文本文件导入python脚本以运行终端命令

时间:2020-07-12 16:00:19

标签: python

我想将文本文件导入python脚本,然后执行if条件,如下所示:

假设我在example.txt文件中有此文件

os: ubuntu
required: no

我想这样做:

if os =="ubuntu" and if required== "no":
 (exec terminal command);
elif os =="debian" & if required== "yes":
 (exec another terminal command);

忽略语法错误,这只是让您了解。

编辑

由于@zyad osseyran,我设法得到了它。

f = open("example.txt", "r")

for x in f:
    x = x.split(':') 
    atribute = x[0]
    value = x[1]

我怎样才能做到这一点,把它变成字典?而且,如何从此处获取值以建立IF条件?

2 个答案:

答案 0 :(得分:1)

    f = open("demofile.txt", "r")

    for x in f:
      x = x.split(':') 
      attribute = x[0]
      value = x[1]

https://www.w3schools.com/python/python_file_open.asp

https://www.w3schools.com/python/ref_string_split.asp

只需按好礼的顺序订购它们,您就可以 您的if陈述 https://www.w3schools.com/python/python_dictionaries.asp

答案 1 :(得分:1)

为了将值保存到字典中,可以执行以下操作:

config = dict()                   # construct an empty dictionary. Fill it with key-value pairs a every iteration
f = open("demofile.txt", "r")
for x in f:
   x = x.split(':') 
   attribute = x[0].strip()       # .strip() removes preceding and trailing whitespaces
   value = x[1].strip()
   config[attribute] = value      # save the attribute and its value to the dictionary

在这种情况下,config是字典,其所有分配给attribute的值都作为键,而相应的value则是值。我还向您阅读的项目中添加了.strip()方法,以删除所有空白(由于example.txt的格式设置,x[1]将具有值" ubuntu"和{{1 }},而不是" no""ubuntu")。

现在,您可以像这样构造if语句:

"no"