【问题标题】:Looping over file names with Python使用 Python 循环文件名
【发布时间】:2020-01-30 06:01:41
【问题描述】:

我有 200 个文件我想用 Python 修改,命名为“1.json”、“2.json”、“3.json”……我正在尝试创建一个循环来打开和修改它们。我没有设法用“for i in range(1, 200):”来做到这一点,所以我尝试了以下方法。

myList = {"1.json", "2.json", "3.json"}
for toImport in myList:
    with open("path1" + toImport) as f:
        json_response = json.load(f)


for data in json_response:
    try:
        for special_issue in data["specific_issues"]:
            for x in special_issue["bills_by_algo"]:
                resulting_data.append(({"id": x["id"], "committees": x["committees"]}))

    except KeyError as e:
        print(e, "not found in entry.")
        continue

b = pd.DataFrame(resulting_data)
print(b)
b.to_csv(r"path2" +toImport)

现在它不再发出错误消息,但文件没有导出...我应该更改什么?

【问题讨论】:

  • 我已经更正了缩进错误并且它有效。但是我仍然无法导出文件...我在帖子中添加了代码行。

标签: python json loops path


【解决方案1】:

在您编辑之后,我必须编辑答案:

我想您必须将所有响应处理代码缩进 for 循环,因为每次迭代后都会覆盖 json_response

myList = {"1.json", "2.json", "3.json"}
for toImport in myList:

    with open("path1" + toImport) as f:
        json_response = json.load(f)

    resulting_data = []
    for data in json_response:
        try:
            for special_issue in data["specific_issues"]:
                for x in special_issue["bills_by_algo"]:
                    resulting_data.append(
                        ({"id": x["id"], "committees": x["committees"]})
                    )

        except KeyError as e:
            print(e, "not found in entry.")
            continue

    b = pd.DataFrame(resulting_data)
    print(b)
    b.to_csv(r"path2" + toImport)


问题编辑前的旧答案:

您有一个小的 SyntaxError,因为您在 for... 下方的代码需要缩进。

import pandas as pd
import json

myList = {"1.json", "2.json", "3.json"}
for toImport in myList:
    with open("path" + toImport) as f:
        json_response = json.load(f)

【讨论】:

  • 谢谢,我已经改过了,它可以工作了。但是我仍然无法导出文件...我在帖子中添加了代码行。
  • 也许我的编辑有效,您很可能需要在初始 for 循环中缩进 JSON 数据代码。
【解决方案2】:

只需缩进最后两行。

Python 要求代码块缩进。在这种情况下,由于您需要循环中的 with 语句,因此您希望它与它的依赖项一起缩进

【讨论】:

  • 谢谢 Marlow,你能解释一下缩进是什么意思吗?
  • 缩进是在行的左边添加一些填充,就像一个段落!通常是 4 个空格或一个制表符
【解决方案3】:

存在缩进错误。试试这个:

import pandas as pd
myList = {'1.json', '2.json', '3.json'}
for toImport in myList:
    with open('path'+toImport) as f:
        json_response = json.load(f)

【讨论】:

    【解决方案4】:

    其他答案指出存在缩进错误。但是代码不好,因为您必须手动列出所有文件。这是一个更完整的解决方案,它遍历文件夹并仅处理 JSON 文件:

    import os
    
    folder = os.path.join('.', 'path/to/data')
    
    for r, d, f in os.walk(folder):
        for file in f:
            if '.json' in file:
                with open(file) as f:
                    # do things with f
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 2020-10-31
      • 2021-10-23
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多