【问题标题】:FileNotFoundError: [Errno 2] No such file or directory: errorFileNotFoundError:[Errno 2] 没有这样的文件或目录:错误
【发布时间】:2019-12-12 20:43:19
【问题描述】:

我使用以下代码遍历多个文件夹以获取每个文件夹中的任何 JSON 文件:

def get_all_jobs():
    for root_dir, _, file_names in os.walk(r'path'):
        for file_name in file_names:
            if file_name.endswith('.json'):
                all_files = (f'{root_dir}/{file_name}')
                for file in all_files:
                    with open(file_name, 'r', encoding="utf8") as json_file:
                        read_content = json.loads(json_file.read())

我得到了这个错误:

FileNotFoundError: [Errno 2] No such file or directory:

并且没有一个文件夹可以提供一个路径,但我有很多文件夹,其中有文件。我该如何解决这个问题?

【问题讨论】:

标签: python file-not-found


【解决方案1】:

查找有关 glob here 的信息。 glob 将转义所有内部目录并递归匹配我们的模式。

def get_all_jobs():    
    for json_file in glob.iglob(path+"/**/*.json".replace('/',os.path.sep),recursive=True):
        with open(json_file, 'r', encoding="utf8") as jf:
            read_content = json.loads(jf.read())

Note: 这里path 是您有多个文件夹的基本目录,其中包含您的 json 文件。

说明:

这里 glob 转到您的基本目录 path ,从那里递归地转到所有子文件夹并检查是否有任何文件包含 .json 扩展名,如果有,则给出该文件的完整路径。

【讨论】:

  • 我仍然遇到同样的错误,因为我没有一个文件路径。我有一个包含许多文件夹的文件夹的路径,每个文件夹都有另一个包含文件的文件夹。所以我不能在这里给出路径“for json_file in glob.iglob(path+"/**/*.json".replace('/',os.path.sep),recursive=True"
  • 您不需要为单个文件提供路径,在我的代码中,“路径”是一个包含多个文件夹和多个 json 的基本目录。所以 /**/ 将通配所有子目录, *.json 将通配文件名。所以最后你会在 json_file 中得到一个 json 文件的完整路径。
  • 我使用了您提供的代码,但仍然没有修复错误“没有这样的文件或目录:”我的代码 def get_all_jobs(): for root_dir, _, file_names in os.walk(path ): for file_name in file_names: if file_name.endswith('.json'): all_files = (f'{root_dir}/{file_name}') for json_file in glob.iglob(r'path'"/**/*. json".replace('/',os.path.sep),recursive=True): with open(file_name, 'r', encoding="utf8") as jf: read_content = json.loads(jf.read() ) 打印(read_content)
  • 您不必使用 os.walk 并检查它是否也以 .json 结尾,我正在编辑我的答案。我假设“路径”是您的基本目录?
  • 这篇文章解决了你的问题吗?如果是这样,请不要忘记accept它,只需单击其左侧的复选标记即可。
猜你喜欢
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2019-04-01
相关资源
最近更新 更多