簡體   English   中英

使用 Python 遍歷文件名

[英]Looping over file names with 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)

現在它不再發出錯誤消息,但文件沒有導出......我應該改變什么?

只需縮進最后兩行。

Python 要求代碼塊縮進。 在這種情況下,由於您想要循環中的 with 句子,您將希望它與它的依賴項一起縮進

存在縮進錯誤。 嘗試這個:

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)

編輯后,我必須編輯答案:

我想您必須將所有響應處理代碼縮進 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)

正如其他答案所指出的那樣,存在縮進錯誤。 但是代碼不好,因為您必須手動列出所有文件。 這是一個更完整的解決方案,它遍歷文件夾並僅處理 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM