[英]Why am i getting this error while trying to open json file?
这是我的代码。 我正在尝试 go 通过文件夹中的所有 json 文件,漂亮地打印它们并写入 output txt 文件。
> import json import os
>
> directory = os.listdir('D:/py/NFT/project/output/metadata/')
> for file in directory:
> with open(file) as jsonfile:
> parsed = json.load(jsonfile)
> conv = json.dumps(parsed, indent=4, sort_keys=True)
> out = open('outputfile' , 'a')
> out.write(conv)
但我收到一个错误:
Traceback (most recent call last): File "d:\py\NFT\project\m.py", line 6, in <module>
with open(file) as jsonfile: FileNotFoundError:
[Errno 2] No such file or directory: '1.json'
在一个文件夹中有.json 文件 - 1.json, 2.json, 3.Z466DEEC76ECDF324FCA6DZ38751
这一点都不奇怪。 os.listdir
返回的文件名只是文件名,而不是路径。 您必须添加路径:
import json import os
path = 'D:/py/NFT/project/output/metadata/'
for file in os.listdir(path):
with open(os.path.join(path,file)) as jsonfile:
os.listdir
返回目录中所有文件的列表,但只是文件名,而不是绝对路径。 当您open
它们时,由于它们不在您的主 python 文件所在的目录中,因此存在问题。
您需要在开头添加绝对路径部分
import json import os
directory = os.listdir('D:/py/NFT/project/output/metadata/')
for file in directory:
with open(f"D:/py/NFT/project/output/metadata/{file}") as jsonfile:
parsed = json.load(jsonfile)
conv = json.dumps(parsed, indent=4, sort_keys=True)
out = open('outputfile' , 'a')
out.write(conv)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.