简体   繁体   中英

Writing to a specific row in a csv, Python 3

I currently have a list structured as: x=['a,b,c,d','e,f,g,h'] And I would like to have each element (between '') to be written to separate rows and each comma separated value placed within a respective cell within that row.

Currently my code adds the full contents of the list 'x' to the top row and i dont know how to fix it.

use a generator comprehension (splitting each text of your list according to commas) as an argument to csv.writerows like this:

import csv

x=['a,b,c,d','e,f,g,h']

with open("output.csv","w",newline="") as f:
    cw = csv.writer(f)
    cw.writerows(l.split(",") for l in x)

A short - and to be honest propably not the most beautiful - piece of code:

x=['a,b,c,d','e,f,g,h']
for ROWS in x:
    print("Handling row", ROWS)
    ROWS = str(ROWS)
    ROW_NEW = []
    if ROWS.count(",") > 0:
        for COLS in ROWS.split(","):
            ROW_NEW.append(COLS)
    print("Resulting row: " + str(ROW_NEW))

Instead of "print", you can use writerow() from the csv module (details here: https://docs.python.org/3.5/library/csv.html )

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