【发布时间】:2016-08-21 03:50:56
【问题描述】:
我正在尝试打开位于当前工作目录 (cwd) 之外的目录中的 JSON 文件。我的设置:Windows 上的 Python3.5(使用 Anaconda)。
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 '/'
【问题讨论】:
-
为什么投反对票?我很高兴重写这个问题。
-
您是否尝试过使用 \ 而不是 / 。 Windows 使用前者作为路径分隔符。关于否决票,现在在这里似乎相当普遍 - 对任何听起来不好的东西投反对票,甚至没有礼貌地发表评论。
-
@PranavRai 我做了,它会导致相同的错误消息。我似乎 open() 命令正在查找 cwd 而不是数据目录。
-
@PranavRai,pathlib 执行路径规范化以将斜杠替换为 Windows 路径的反斜杠。 (此外,Windows API 允许交替使用斜杠和反斜杠,但原始
\\?\路径需要反斜杠除外。)这里的问题是使用name属性,它只是基本文件名,而不是str(file),后者是完全合格的路径。在 3.6 中,pathlib 支持新的__fspath__协议,因此open(file)将起作用,这将使做正确的事情变得更简单。 -
是的,谢谢 :) 在调试器上工作时才意识到
标签: json windows python-3.x