【发布时间】: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:
并且没有一个文件夹可以提供一个路径,但我有很多文件夹,其中有文件。我该如何解决这个问题?
【问题讨论】:
-
您可以使用 glob 模块转义所有目录并仅获取以 .json 结尾的文件。检查此相关答案stackoverflow.com/a/50721824/6798902
-
在询问有关错误的问题时,始终包括(复制粘贴,作为文本)full 和 complete 错误输出。您还应该包括详细信息,例如您尝试打开的 what 文件。也请花一些时间阅读how to ask good questions 和this question checklist。最后请学习如何创建minimal reproducible example。
-
for file in all_files将遍历在它上面的行中创建的字符串中的字符。
标签: python file-not-found