简体   繁体   中英

Append data to csv columns python

How the csv looks like

col1,col2,col3,col4,col5
value1,value2,value3,value4,value5
,,value6,value7,value8,value9
,,value10,value11,value12,value13

how my function looks so far

def append(file, value1, value2):
    with open(file, 'a',) as file:
        writer = csv.writer(file, quoting=csv.QUOTE_NONE, escapechar=' ')
        writer.writerow([value1, value2])

The append function is called inside a function where value 1 and value 2 are passed from.

If the csv file looks like the below, the function does the job

col1,col2,col3,col4,col5
value1,value2,value3,value4,value5

How could I write to a particular cell for as long as value1 and value2 are passed in. Don't need to wory about the values being passed, just for the function to introduce the arguments.

the csv would look like:


col1,col2,col3,col4,col5
value1,value2,value3,value4,value5
,,value6,value7,value8,value9
,,value10,value11,value12,value13

Expected result


col1,col2,col3,col4,col5
value1,value2,value3,value4,value5
argument1,argumen2,value6,value7,value8,value9
argument3,argument3,value10,value11,value12,value13

That way is how I was learned and is so easy:

def append_csv(file, *argv):
    my_line = ','.join([elem for elem in argv]) + '\n'
    file.write(my_line)
  
my_file = open('my_csv_file.csv', 'a')
append_csv(my_file, 'val1', 'val2', ... , 'valN')
my_file.close() # you need to close to save the changes.

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