is there a way to put all my list into one cell in my CSV file?

Viewed 26

is there a way to put all my list into one cell in my CSV file? The reason for doing this is because the variable belongs to a single data.

row1 = [(1.1603180714482149, 103.9129638389025),
 (1.160308848641466, 103.912935217908),
 (1.1602761166689228, 103.91294562159307),
 (1.1602853394755797, 103.91297424258724),
 (1.1603180714482149, 103.9129638389025)]

# This is the code that i ran

from csv import writer
def append_list_as_row(file_name, list_of_elem):
    
# Open file in append mode
    with open(file_name, 'a+', newline='') as write_obj:
       
 # Create a writer object from csv module
        csv_writer = writer(write_obj)
       
 # Add contents of list as last row in the csv file
        csv_writer.writerow(list_of_elem)

append_list_as_row('xxx.csv', row1)

below here isn't a code, i am just trying to show the result clearly

The result i got was
A                                         B
(1.1603180714482149, 103.9129638389025)   (1.160308848641466, 103.912935217908)

i am trying to get 

A
(1.1603180714482149, 103.9129638389025), (1.160308848641466, 103.912935217908), xxxx,xxx,xx
1 Answers

When you use writerow(), each list element is a separate fields in the CSV. If you want everything in one field, you need to make it a single list element. So put list_of_elem inside another list.

csv_writer.writerow([list_of_elem])

Note that when it does this it will add another set of [] around the field, since it's a list.

Related