Simple Machines Community Forum

General Community => Scripting Help => Topic started by: Mark011 on August 23, 2023, 03:53:11 AM

Title: Creating a CSV File in Python: Need Guidance and Code Example
Post by: Mark011 on August 23, 2023, 03:53:11 AM
I'm relatively new to Python and I'm trying to create a CSV file from data within my program. I've read a bit about the csv module, but I'm not entirely sure about the best approach to create a CSV file and populate it with data. Could someone guide me through the process and provide a code example?

Let's say I have a list of dictionaries containing data about products, like so:

products = [
    {"ProductID": 1, "ProductName": "Widget A", "Price": 10.99},
    {"ProductID": 2, "ProductName": "Widget B", "Price": 15.99},
    {"ProductID": 3, "ProductName": "Widget C", "Price": 8.49}
]

I want to create a CSV file named products.csv with the following headers: "ProductID", "ProductName", and "Price", and then populate it with the data from the products list.  I tried looking for a solution by visiting numerous forums and websites like Scaler, but I was unable to do so. Could someone provide me an example of how to accomplish this using the Python csv module? I would be very grateful for any advice!

Title: Re: Creating a CSV File in Python: Need Guidance and Code Example
Post by: @rjen on August 23, 2023, 05:41:09 AM
Does this question in any way relate to SMF?
Title: Re: Creating a CSV File in Python: Need Guidance and Code Example
Post by: Chen Zhen on August 24, 2023, 10:50:42 AM
Try searching stackoverflow for things like that:
https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files#:~:text=To%20create%20and%20write%20into%20a%20csv%20file&text=writerow(%7B%22Names%22%3A%22,is%20your%20respective%20key%20value.

You need to look at examples & take a stab at it.