Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用循环从目录导入多个文件_Python_Json_For Loop_Import - Fatal编程技术网

Python 使用循环从目录导入多个文件

Python 使用循环从目录导入多个文件,python,json,for-loop,import,Python,Json,For Loop,Import,我正试图从一个目录中导入多个.json文件,结果被卡住了。目录中不仅仅包含.json文件。我意识到我需要使用循环导入,但我对所有这些都很陌生。有什么帮助吗?以下是我迄今为止的代码: import os path = "/Users/jkelson/Desktop/JsonFiles/Project3" directory = os.listdir(path) for x in directory: if x.endswith('.json'): with open(x)

我正试图从一个目录中导入多个.json文件,结果被卡住了。目录中不仅仅包含.json文件。我意识到我需要使用循环导入,但我对所有这些都很陌生。有什么帮助吗?以下是我迄今为止的代码:

import os
path = "/Users/jkelson/Desktop/JsonFiles/Project3"
directory = os.listdir(path)

for x in directory:
    if x.endswith('.json'):
        with open(x) as input_file:
            jsondata = json.load(input_file)
你是说把它改成这个

import os
path = "/Users/jkelson/Desktop/JsonFiles/Project3"
directory = os.path.join(path, x)

for x in directory:
    if x.endswith('.json'):
        with open(x) as input_file:
            jsondata = json.load(input_file)
很明显我是新手,我道歉。这也是我的第一篇帖子,所以请原谅我在社区评论中犯了错误

在这个目录中有多个.json文件,它们的名称各不相同,我正试图打开它们并将它们存储在一个数据框架中进行分析

import os
path = "/Users/jkelson/Desktop/JsonFiles/Project3"
directory = os.listdir(path)

for x in directory:
    if x.endswith('.json'):
        full_path = os.path.join(path, x)
        with open(full_path) as input_file:
            jsondata = json.load(input_file)

正如zondo指出的那样,发生错误是因为您试图打开一个在您运行的目录中不存在的文件。您需要在
open()
语句中提供文件的完整路径。考虑修改一下:

full_path = os.path.join(path, x)
with open(full_path) as input_file:
     # Rest of your code here

你在这方面“卡住”了什么?到目前为止,您所拥有的有什么问题吗?我在()6中得到了这个错误:如果x.endswith('.json'):7以open(x)作为输入文件:-->8 jsondat=json.load(输入文件),那么ValueError Traceback(最近一次调用)问题是您使用的是文件名,而不包括路径。请使用
os.path.join(path,x)
Post更新问题中的问题。否,在循环中。运行
open(x)
时会发生错误,因为
x
只是文件名,而不是文件的完整路径。