テキストファイルを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条件を作成する方法は?
値をディクショナリに保存するには、次のようにします。
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.SQLをフォーマットする方法から、任意の空白を除去するために、読み項目に方法が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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加