我正在尝试打开位于当前工作目录(cwd)以外的目录中的JSON文件。我的设置:Windows(使用Anaconda)上的Python3.5。
from pathlib import *
import json
path = Path("C:/foo/bar")
filelist = []
for f in path.iterdir():
filelist.append(f)
for file in filelist:
with open(file.name) as data_file:
data = json.load(data_file)
在此设置中,我具有以下值:
file >> C:\foo\bar\0001.json
file.name >> 0001.json
但是,我收到以下错误消息:
---> 13 with open(file.name) as data_file:
14 data = json.load(data_file)
FileNotFoundError: [Errno 2] No such file or directory: '0001.json'
这是我到目前为止尝试过的:
使用.joinpath()在打开命令中将目录添加到文件名:
with open(path.joinpath(file.name)) as data_file:
data = json.load(data_file)
TypeError: invalid file: WindowsPath:('C:/foo/bar/0001.json')
使用.resolve(),因为它可以将CSV文件加载到Pandas中。在这里没有工作。
for file in filelist:
j = Path(path, file.name).resolve()
with open(j) as data_file:
data = json.load(data_file)
由于我在Windows上的写入路径为(是的,文件位于该目录中):
path = Path("C:\\foo\\bar") #resulted in the same FileNotFoundError above.
像这样实例化路径:
path = WindowsPath("C:/foo/bar")
#Same TypeError as above for both '\\' and '/'
最佳答案
接受的答案有很多冗余-重新收集生成器,并与带有pathlib.Path的语句混合。
pathlib.Path是处理路径的绝佳解决方案,特别是如果我们要创建适用于Linux和Windows的脚本时。
# modules
from pathlib import Path
import json
# static values
JSON_SUFFIXES = [".json", ".js", ".other_suffix"]
folder_path = Path("C:/users/user/documents")
for file_path in folder_path.iterdir():
if file_path.suffix in JSON_SUFFIXES:
data = json.loads(file_path.read_bytes())
只需为新用户添加修改。 pathlib.Path适用于Python3。