Home > Enterprise >  Write 3 variables to 3 columns in a CSV
Write 3 variables to 3 columns in a CSV

Time:04-18

I'm getting tripped up by what I thought would be a simple task.

I have 3 variables:

set_number, price, split_html

I'd like to write them to a CSV with headers named SKU,RRP, SPECS(already present in CSV).

I've tried multiple approaches, including adding the variables to a pandas df, but have gotten poor results from all my attempts. I'm not stuck on using pandas, so any method advised works for me.

The other requirement is that the data is written to new row on each run of this function as the variables will change. Also, the split_html variable contains html code.

Code I've tried:

data = set_number, price
df = pd.DataFrame(columns= ['SKU', 'RRP', 'SPEC'])
df = pd.DataFrame(data)
df

This writes each variable to a new row within the same column. Haven't tried writing to a csv yet since the df is formatted wrong.

# datarow = set_number,price,split_spec
# with open(r'setspec.csv', 'a', newline= '') as csvfile:
#     writer = csv.writer(csvfile)
#     datarow =[str(set_number), str(price), str(split_spec)]
#     writer.writerow(datarow) 

This code writes each variable in a column, but produces inconsistent results. Most times it skips the first three columns with headers, and writes to 3 new columns. So it skips A,B,C and writes in column DEF.

CodePudding user response:

with open(r"setspec.csv","a") as csvfile:
    csvfile.write(str(set_number) ',' str(price) ',\"' str(split_spec) '\",\n'
  • Related