Python "with open" 语句以目录作为名称创建文件,但不在实际目录中
Python "with open" statement creates file with directory as name, but not in the actual directory
我想使用以下代码将 JSON-数据保存到一个(在不存在之前)文件,该文件适用于 Python 3.6.5:
with open("Samples\{}.json".format(id), "w", encoding="utf-8") as f:
json.dump(labels, f, ensure_ascii=False, indent=4)
这将在 Samples 文件夹中创建一个新的 .json 文件。
现在我在 Python 3.7.3 中尝试了相同的方法,但不是在所述目录中创建一个新的 .json 文件,而是在 "Samples\xyz.json" 目录中创建一个名称类似于 "Samples\xyz.json" 的文件 python 代码是 运行 (运行 在 jupyter notebook 中)。
我已经尝试了以下方法,但在创建文件时出现了同样的问题,文件名是目录:
f = open(os.path.expanduser(os.path.join("Samples/{}.json".format(document_id)))
json.dump(labels, f, ensure_ascii=False, indent=4)
如何使用 Python 3.7.3 在所需目录中创建新的 .json 文件?
使用路径库和 f 字符串:
from pathlib import Path
document_id = 100 # Random id here ...
sample_file = Path("Samples") / f"{document_id}.json"
sample_file.parent.mkdir(exist_ok=True)
with sample_file.open("w", encoding="utf-8") as f:
json.dump(labels, f, ensure_ascii=False, indent=4)
我想使用以下代码将 JSON-数据保存到一个(在不存在之前)文件,该文件适用于 Python 3.6.5:
with open("Samples\{}.json".format(id), "w", encoding="utf-8") as f:
json.dump(labels, f, ensure_ascii=False, indent=4)
这将在 Samples 文件夹中创建一个新的 .json 文件。
现在我在 Python 3.7.3 中尝试了相同的方法,但不是在所述目录中创建一个新的 .json 文件,而是在 "Samples\xyz.json" 目录中创建一个名称类似于 "Samples\xyz.json" 的文件 python 代码是 运行 (运行 在 jupyter notebook 中)。
我已经尝试了以下方法,但在创建文件时出现了同样的问题,文件名是目录:
f = open(os.path.expanduser(os.path.join("Samples/{}.json".format(document_id)))
json.dump(labels, f, ensure_ascii=False, indent=4)
如何使用 Python 3.7.3 在所需目录中创建新的 .json 文件?
使用路径库和 f 字符串:
from pathlib import Path
document_id = 100 # Random id here ...
sample_file = Path("Samples") / f"{document_id}.json"
sample_file.parent.mkdir(exist_ok=True)
with sample_file.open("w", encoding="utf-8") as f:
json.dump(labels, f, ensure_ascii=False, indent=4)