简体   繁体   中英

Writing variables to a CSV row python

I have a simple program that does some calculations inside a for loop on a dataframe.

The program prints the results of 5 variables, eg a,b,c,d,e after each iteration

I simply want to append these 5 values in new rows to a CSV each time the loop runs but I can't figure out how to do it! I've tried with a basic csv write but they always appear in the same column, rather than in a row together

Any help would be appreciated

    csvRow = [x, ctr, clicks, spend, bidTotal, cpm, cpc]
    csvfile = "data.csv"
    with open(csvfile, "a") as fp:
    wr = csv.writer(fp, dialect='excel')
    wr.writerow(csvRow)

Your code appears to work fine if properly tabulated:

import csv
x, ctr, clicks, spend, bidTotal, cpm, cpc = 1, 2, 3, 4, 5, 6, 7
csvRow = [x, ctr, clicks, spend, bidTotal, cpm, cpc]
csvfile = "data.csv"
with open(csvfile, "a") as fp:
    wr = csv.writer(fp, dialect='excel')
    wr.writerow(csvRow)
    wr.writerow(['a', 'b', 'c', 'd', 'e', 'f', 'g'])

open(csvfile, 'r').read() then returns:

'1,2,3,4,5,6,7\\r\\na,b,c,d,e,f,g\\r\\n'

-- as expected.

If it's still not working for you try to provide a minimal example that reproduces the problem. Remember (with open(... "a") ) you are appending to an existing file so if it looks wrong this may be a leftover problem from a previous version of the programme.

the blank lines are there because of a limitation in the csv module when running windows:

Python 3:

with open(csvfile, "a", newline='') as fp:

Python 2:

with open(csvfile, "ab") as fp:

read related Q&A: portable way to write csv file in python 2 or python 3

To write values to a file, you first need to open the file to put the values in:

file = open('filename.csv', 'a') #opens a file for appending

Then you must write to the file on every iteration of your loop:

file.write('{}, {}, {}, {}, {}\n'.format(a, b, c, d, e))    #writes a formatted string to the file

And close the file when you are done with it:

file.close()

Variable----user_id

dict: --- Curso['ultima']['key']

constant: 'hola'

csvRow = [user_id, NCurso, Curso['ultima']['key'], 'hola']
csvfile = "digraph.csv"
with open(csvfile, "a", newline='') as fp:
     wr = csv.writer(fp, dialect='excel')
     wr.writerow(csvRow)

Result:

1,Mate,131313,hola    
2,Fisica,121313,hola    
3,Cal,131334,hola

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM