R
R
Roman2016-09-30 23:15:27
Python
Roman, 2016-09-30 23:15:27

Why is csv generated incorrectly?

Hello. What is wrong with my code? I parse xml into csv, selected all the tags I need. When I open my csv file I get the line offset. It grows vertically. An example in the image below
5cd86a9335ff4e6a9ddb790fa30187d3.png
And the more tags in the table header, the lower the text from the tags is shifted vertically.
Code example:

for place in root.findall('Place'):
    for identity in place.findall('Identity'):
        row0 = {}
        for placeid in identity.findall('PlaceId'):
            header.add(placeid.tag)
            row0[placeid.tag] = placeid.text
        places_data.append(row0)
for place in root.findall('Place'):
  for locationlist in place.findall('LocationList'):
    for location in locationlist.findall('Location'):
        for address in location.findall('Address'):
            for parsed in address.findall('Parsed'):
                row1 = {}
                for countrycode in parsed.findall('CountryCode'):
                    header.add(countrycode.tag)
                    row1[countrycode.tag] = countrycode.text
                    places_data.append(row1)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri, 2016-10-01
@ro25man

Because you are in a hurry to add a row to "places_data". At the beginning, we collected all the "PlaceId" and added them to "places_data", then all the "CountryCode" ... (repeat for each heading) from this we get such a "ladder".
Seems like this should work:

for place in root.findall('Place'):
    row = {}

    for identity in place.findall('Identity'):
        for placeid in identity.findall('PlaceId'):
            header.add(placeid.tag)
            row[placeid.tag] = placeid.text
            
    for locationlist in place.findall('LocationList'):
        for location in locationlist.findall('Location'):
            for address in location.findall('Address'):
                for parsed in address.findall('Parsed'):
                    for countrycode in parsed.findall('CountryCode'):
                        header.add(countrycode.tag)
                        row[countrycode.tag] = countrycode.text
    places_data.append(row)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question