[Python] Regardless, the double quotes are written to a CSV file in Python [duplicate]

Discussão em 'Python' iniciado por Stack, Abril 25, 2025.

  1. Stack

    Stack Membro Participativo

    My Python script reads data in JSON format, and then save data to the csv file (output.csv). Before it writes data to the csv file, it calls the function remove_double_quotes() to remove the double-quotes. When it's done, I still get the double-quotes in the file output.csv.

    import json
    import csv

    # Sample JSON data
    json_data = '''
    {
    "root":
    {
    "root":
    {
    "total-count": "2",
    "row":
    [
    {
    "cus_id": "1234",
    "first_name": "John",
    "last_name": "Smith",
    "add_1": "2369 Lake St",
    "add_2": "",
    "city": "New York",
    "state": "NY",
    "zip": "10003",
    "company": "Joe Supplier, Inc."
    },
    {
    "cus_id": "3456",
    "first_name": "Mary",
    "last_name": "Hope",
    "add_1": "208 Mountain View Way",
    "add_2": "APT-2",
    "city": "San Francisco",
    "state": "CA",
    "zip": "93102",
    "company": "Sunnywood Logistics, LLC."
    }
    ]
    }
    }
    }
    '''

    # Load JSON data
    data = json.loads(json_data)

    # Function to remove double quotes from values
    def remove_double_quotes(data):
    if isinstance(data, dict):
    return {key: remove_double_quotes(value) for key, value in data.items()}
    elif isinstance(data, list):
    return [remove_double_quotes(item) for item in data]
    elif isinstance(data, str):
    return data.replace('"', '')
    else:
    return data

    # Processed data without double quotes
    processed_data = remove_double_quotes(data['root']['root']['row'])

    # Write to CSV
    csv_file = 'output.csv'
    with open(csv_file, mode='w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames = processed_data[0].keys())
    writer.writeheader()
    writer.writerows(processed_data)

    print(f"Data has been written to {csv_file} successfully!")


    Now, open the output.csv file as below:

    cus_id,first_name,last_name,add_1,add_2,city,state,zip,company
    1234,John,Smith,2369 Lake St,,New York,NY,10003,"Joe Supplier, Inc."
    3456,Mary,Hope,208 Mountain View Way,APT-2,San Francisco,CA,93102,"Sunnywood Logistics, LLC."


    I don't want the double-quotes around "Joe Supplier, Inc." and "Sunnywood Logistics, LLC."

    What I did wrong????

    Thank you.

    Continue reading...

Compartilhe esta Página