首页 > 解决方案 > 用 Python 循环文件名

问题描述

我有 200 个文件我想用名为“1.json”、“2.json”、“3.json”的 Python 修改......我正在尝试创建一个循环来打开和修改它们。我没有设法用“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)

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

标签: pythonjsonloopspath

解决方案


只需缩进最后两行。

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


推荐阅读