Open JSON files in different directory - Python3, Windows, pathlib

rau*_*sch 4 windows json python-3.x

I am trying to open JSON files located in a directory other than the current working directory (cwd). My setting: Python3.5 on Windows (using 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)
Run Code Online (Sandbox Code Playgroud)

In this setting I have these values:

file >> C:\foo\bar\0001.json
file.name >> 0001.json
Run Code Online (Sandbox Code Playgroud)

However, I get the following error message:

---> 13     with open(file.name) as data_file:
     14         data = json.load(data_file)

FileNotFoundError: [Errno 2] No such file or directory: '0001.json'
Run Code Online (Sandbox Code Playgroud)

Here is what I tried so far:

Use .joinpath() to add the directory to the file name in the open command:

with open(path.joinpath(file.name)) as data_file:
    data = json.load(data_file)

TypeError: invalid file: WindowsPath:('C:/foo/bar/0001.json')
Run Code Online (Sandbox Code Playgroud)

Used .resolve() as that works for me to load CSV files into Pandas. Did not work here.

for file in filelist:
    j = Path(path, file.name).resolve()
    with open(j) as data_file:    
        data = json.load(data_file)
Run Code Online (Sandbox Code Playgroud)

Since I'm on Windows write path as (and yes, the file is in that directory):

path = Path("C:\\foo\\bar") #resulted in the same FileNotFoundError above.
Run Code Online (Sandbox Code Playgroud)

Instantiate path like this:

path = WindowsPath("C:/foo/bar")
#Same TypeError as above for both '\\' and '/'
Run Code Online (Sandbox Code Playgroud)

小智 8

接受的答案有很多冗余 - 重新收集生成器并与带有 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())
Run Code Online (Sandbox Code Playgroud)

只是为新用户添加修改。pathlib.Path 适用于 Python3。


rau*_*sch 5

完整的解决方案;谢谢@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)
Run Code Online (Sandbox Code Playgroud)

这条线也有效:

with file.open() as data_file:
Run Code Online (Sandbox Code Playgroud)