Navigating through filenames using Python

With a collection of 200 JSON files in Python named "1.json", "2.json", "3.json" and so on, I set out to apply modifications using a loop. Unable to achieve the desired result using "for i in range(1, 200):", I decided to pursue an alternative method.


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)

Although now devoid of error messages, the files are not being exported. What adjustments should I make?

Answer №1

Upon reviewing your edits, I see that adjustments need to be made to the answer:

It appears that you should indent all of your response handling code within the for loop, as the json_response variable gets overwritten after each iteration.

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)


Previous answer prior to the edit:

You have a small SyntaxError caused by improper indentation below the for loop.

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)

Answer №2

Ensure proper indentation for Python code blocks.

In Python, it is important to properly indent your code blocks. For example, if you want to include the 'with' statement within a loop, make sure to indent it along with its related lines of code.

Answer №3

An issue with indentation has been detected. Below is a corrected version:

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)

Answer №4

It has been pointed out that there is an indentation error in the code, but a bigger issue is having to list all files by hand. A better approach would be to loop over a folder and process only JSON files:

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:
                # perform actions on f

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain 2 text values from HTML by extracting with Python Selenium and ChromeDriver

I am using a webdriver to extract necessary data from a webpage, but I have encountered an issue. Specifically, I need help with retrieving values 61 and 70% from the provided content below. I have attempted driver.find_element_by_xpath("//p[@class="stock- ...

Transforming Python AES into Node JS

I've encountered a challenge trying to make existing legacy Python code encrypt/decrypt data the same way as NodeJS. Although the first 16 characters are correctly decoded, I'm facing issues with the rest of the process. Here's the Python c ...

Exploring the capabilities of data processing in Node.js

I've been attempting to read data from a locally stored JSON file, organize it into individual JS objects, and add them to a queue. However, I'm struggling to find a way to test my parsing function to ensure it's functioning correctly. My cu ...

Tips for iterating through both a list and dictionary simultaneously within a for loop at the template level in Django

Within my view.py, there is a function that retrieves two variables: a dictionary named ca and a list named categories: def eventcateg_detail(request): ca = EventTypeCategory.objects.values() categories =[] for i in range(0, len(ca)): p ...

Utilizing Python's regular expressions for parsing and manipulating Wikipedia text

I am attempting to convert wikitext into plain text using Python regular expressions substitution. There are two specific formatting rules for wiki links: [[Name of page]] [[Name of page | Text to display]] (http://en.wikipedia.org/wiki/Wikipedia:Cheat ...

Utilizing Json and Gson for Android Development

Could someone please explain the distinction between JSON and GSON to me? I keep coming across the term GSON while researching JSON, but I'm not sure how they differ. I'm confused about the specific differences between the two. Additionally, I& ...

Error encountered when attempting to compile tutorial example using json::object!: identifier expected, keyword found

This code snippet showcases usage of the json crate with annotated comments: #[macro_use] extern crate json; fn main() { let mut data = object!{ foo: false, bar: null, answer: 42, ...

The jsTree rendering does not properly display the "closed" state of the JSON data nodes

Currently, I am in the process of setting up a jsTree instance to display a directory listing from a file server. However, I am encountering challenges with getting "sub-folder" or "sub-directory" nodes within the jsTree to show as open-able. Even though ...

Extracting information from a webpage

I am trying to extract the text from the XPath provided below using Selenium. However, I keep encountering the following traceback error: date = driver.find_element_by_xpath('//[@id="General"]/fieldset/dl/dd[5]/text()').text() print(date) Error ...

Trouble accessing contacts on LinkedIn

When attempting to retrieve the LinkedIn connections for a logged-in user, I used the following API Request: However, I encountered an error message: { "errorCode": 0, "message": "Access to connections denied", "requestId": "OFP0JOLOHO", "status" ...

Having trouble making JSON work alongside Ajax and jQuery?

In my JavaScript, I have the following code snippet... $.ajax({ type: 'POST', url: 'http://www.example.com/ajax', data: {email: val}, success: function(response) { alert(response); } }); The PHP fil ...

Exploring Selenium With Various Network Connections

I have a Linux system with two different interfaces (such as eth0 and tap0). I'm trying to run two separate instances of selenium phantomjs browsers simultaneously, each using a different interface. Is it possible to choose which interface to use in s ...

Jackson utilizes varying deserializers for unique scenarios

Is it possible to utilize distinct deserializers for varying scenarios? For instance: public class Student { @JsonDeserialize(using = SomeAdeserializer.class) @JsonProperty("dob") Date dateOfBirth; } Could a different deserializer like S ...

The second iteration of the while loop in Selenium throws an error

I am encountering an issue with my code. The first iteration of the while loop runs smoothly, but I receive an error on the second iteration. How can I resolve this issue and make it work properly? import time from selenium import webdriver from selenium. ...

Using pre-existing CSS state background colors in GTK3

I am currently in the process of adapting a PyGTK2 application. This particular application performs tasks such as: self.normal_color = editor.style.base [Gtk.STATE_NORMAL] self.insensitive_color = editor.style.base [Gtk.STATE_INSENSITIVE ...

Could anyone provide some insight into this recursive function? I grasp the concept of the function counting down to zero, but I struggle to comprehend how it manages to count back up to

function displayNumberPattern(first, second) { if (first == 0 || first < 0) { console.log(first); return; } console.log(first); displayNumberPattern(first - second, second); console.log(first); } ...

What is the purpose of including localId elements when performing a bulk create issue operation in Jira's API?

As I work on taskLists within the issues, I've noticed that localIds are necessary according to the json schema. It's puzzling because ids don't seem required unless they're being referenced. Can you provide insight into the technical r ...

Compiling Python 3.4 with emscripten on Linux (encountering linkage errors)

I am in the process of building Python 3.4 from source using emscripten. After successfully installing emscripten and setting up a build folder outside the source tree, I have followed these steps: Ran configure: $ emconfigure ../Python-3.4.3/configur ...

Error in decoding JSON while creating an index in Azure Search

I'm currently utilizing the django framework and attempting to set up an index in the Azure portal through their REST API guide. However, upon sending my post request, I encountered the following error: JSONDecodeError at /createIndex Here is the m ...

Analyzing PCAP files with Python 2.6

I am looking to analyze information within a data packet captured. I have tried using examples to test my code, but it always results in an error. Below is the snippet of code that causes trouble: import dpkt import sys f = open('test.pcap') pc ...