将扩展附加到 os.environ.get 的输出

我是 python 的新手,我正在尝试创建一个以环境变量命名的 json 文件。

的变量称为parent与值galaxy

这就是我的文件的样子。

import json
import sys
import os

Report = os.environ.get('MainReport')

if Report == "Main":
    newFile = os.environ.get('parent')
else:
    newFile = os.environ.get('child')

#####Additional Logic Here############

json_output = json.dumps(output,indent=4)
with open(newFile, "w") as outfile:
    outfile.write(json_output)

print("Output file is generated in the current directory!")
file.close()

当我运行脚本时,它会galaxy按预期在我的当前目录中创建文件。

但我需要命名文件 galaxy.json

我试过了

if Report == "Main":
    newFile = os.environ.get('parent').json

但它抛出这个错误
AttributeError: 'str' object has no attribute 'json'

有没有办法附加.json到输出os.environ.get

回答

使用连接运算符附加字符串。

if Report == "Main":
newFile = os.environ.get('parent') + ".json"

以上是将扩展附加到 os.environ.get 的输出的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>