lundi 1 mars 2021

How to find the length of a string in a row of a csv file?

I have a csv file that has some zip codes that are 5 long and some that are 10. Ex. 54091 / 54091-3412. The zip codes that are 10 long I want to cut down to 5. Here is my code thus far.

import csv
import json

category_nm = "Other Pharmacies"
def csv_to_json(csvFilePath, jsonFilePath):
    dataset = {
        "dataset_id": "???",
        "places": []
    }
    places = []
    cnt = 0
    with open(csvFilePath, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)

        for row in csvReader:
            if row["category_nm"] != category_nm:
                continue
            if len(row['zip_cd'] > 5):
                zip_ = row['zip_cd'](0,5)
            else:
                zip_ = row['zip_cd']
            place = {
                "place_name": category_nm,
                "address": row["address"],
                "city": row["city"],
                "state": row["state_cd"],
                "zip": row["zip_cd"],
                "geo_location": f"{row['latitude']},{row['longitude']}",
                "data": {

                }
            }
            places.append(place)
            cnt += 1
    dataset["places"] = places
    print(cnt)
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonString = json.dumps(dataset, indent=4)
        jsonf.write(jsonString)


csvFilePath = r'pharmacies.csv'
jsonFilePath = r'read.json'
csv_to_json(csvFilePath, jsonFilePath)  

here is the error I am getting

if len(row['zip_cd'] > 5):
TypeError: '>' not supported between instances of 'str' and 'int'

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire