我正在尝试打开位于当前工作目录(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 '/'
完整的解决方案;谢谢@eryksun:
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(str(file) as data_file:
data = json.load(data_file)
该行也可以正常工作:
with file.open() as data_file:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句