【问题标题】:Import multiple files from directory with loop使用循环从目录导入多个文件
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 2022-10-09
    • 2013-04-24
    • 1970-01-01
    • 2019-12-14
    相关资源
    最近更新 更多