【发布时间】:2017-04-28 00:12:27
【问题描述】:
我正在尝试从一个目录中导入多个 .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)
很明显我是新手,我很抱歉。这也是我的第一篇文章,如果我在社区 cets 上犯了错误,请原谅我。
在目录中有多个 .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)
【问题讨论】:
-
您“坚持”了哪些方面?到目前为止,您有什么问题?
-
我收到此错误:ValueError Traceback (最近一次调用最后一次)
in () 6 if x.endswith('.json'): 7 with open(x) as input_file: ----> 8 jsondat = json.load(input_file) -
问题是你使用的文件名没有包含路径。使用
os.path.join(path, x) -
请在问题中发布问题的更新。
-
不,在循环内。运行
open(x)时会发生错误,因为x只是文件名,而不是文件的完整路径。
标签: python json for-loop import