这看起来应该很简单,但还没有找到如何解决这个问题的有效示例。简而言之,我根据脚本生成的列表生成 JSON 文件。我想做的是使用一些变量来运行 dump() 函数,并在特定文件夹中生成一个 json 文件。默认情况下,它当然会转储到 .py 文件所在的同一位置,但似乎找不到单独运行 .py 文件的方法,然后在我选择的新文件夹中生成 JSON 文件:
import json
name = 'Best'
season = '2019-2020'
blah = ['steve','martin']
with open(season + '.json', 'w') as json_file:
json.dump(blah, json_file)
Run Code Online (Sandbox Code Playgroud)
就拿上面的例子来说吧。我想做的是以下内容:
现在我的问题是我找不到在特定文件夹中生成文件的方法。任何建议,因为这看起来确实很简单,但我发现没有任何方法可以做到这一点。谢谢!
Python 的pathlib对于此任务来说非常方便:
import json
from pathlib import Path
data = ['steve','martin']
season = '2019-2020'
Run Code Online (Sandbox Code Playgroud)
新目录和json文件的路径:
base = Path('Best')
jsonpath = base / (season + ".json")
Run Code Online (Sandbox Code Playgroud)
如果目录不存在则创建并写入json文件:
base.mkdir(exist_ok=True)
jsonpath.write_text(json.dumps(data))
Run Code Online (Sandbox Code Playgroud)
这将创建相对于您启动脚本的目录的目录。如果您想要绝对路径,您可以使用Path('/somewhere/Best')
.
如果您想在其他目录中启动脚本并仍然在脚本目录中创建新目录,请使用:Path(__file__).resolve().parent / 'Best'
。
首先,不要在同一个地方执行所有操作,而是使用单独的函数来创建文件夹(如果尚不存在)并转储 json 数据,如下所示:
def write_json(target_path, target_file, data):
if not os.path.exists(target_path):
try:
os.makedirs(target_path)
except Exception as e:
print(e)
raise
with open(os.path.join(target_path, target_file), 'w') as f:
json.dump(data, f)
Run Code Online (Sandbox Code Playgroud)
然后调用你的函数,如下所示:
write_json('/usr/home/target', 'my_json.json', my_json_data)
Run Code Online (Sandbox Code Playgroud)