【问题标题】:Open JSON files in different directory - Python3, Windows, pathlib在不同目录中打开 JSON 文件 - Python3、Windows、pathlib
【发布时间】: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


【解决方案1】:

接受的答案有很多冗余 - 重新收集生成器并与带有 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。

【讨论】:

    【解决方案2】:

    完整的解决方案;谢谢@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:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-25
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2015-08-21
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多