[英]Import text file to python script to run terminal commands
我想將文本文件導入 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 條件?
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
為了將值保存到字典中,您可以執行以下操作:
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"
和" no"
而不是"ubuntu"
和"no"
)。
現在你可以像這樣構造你的 if 語句:
if config['os'] == 'ubuntu' and config['required'] == 'no':
# exec terminal command
elif config['os'] == 'debian' and config['required'] == 'yes':
# exec another terminal command
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.