如何使用 os python 获取另一个文件夹中文件的路径

How to get path of a file in another folder using os python

假设这是我的文件夹结构,

project
    main_folder
         file.py
    json_files_folder
         one.json
         two.json
         three.json

当我 运行 file.py 文件时,它应该获取 json_files_folder 中文件的路径并打开一个文件, 这是我的代码,

import json
import os


try:
    file_path = os.path.dirname(os.path.realpath(__file__))
    filename = file_path + '/' + 'one' + '.json'
    with  open(filename) as file:
        data = json.load(file)
    return data
except:
     return "error"

我应该在 file_path 变量中更改什么才能使此代码正常工作? 提前致谢!

您的 json 文件存在于 json_files_folder 中,因此您需要遍历该路径以获取 json 文件。这是相同的代码:

import json
import os


try:
    file_path = os.path.dirname(os.path.realpath(__file__))
    filename = file_path + '/../json_files_folder/one.json'
    with  open(filename) as file:
        data = json.load(file)
    print (data)
except Exception as ex:
     raise ex

另一个解决方案是使用 Pathlib.Path.

import json
from pathlib import Path


try:
    base = Path(__file__).parent.parent
    filename = base / 'json_files_folder' / 'one.json'
    with  open(filename) as file:
        data = json.load(file)
    print(data)
except:
     return "error"