简体   繁体   中英

How to write list to specific location in CSV file?

Week over week, I want to be able to write the contents from a list I have to a CSV file. Essentially, I need to find a way to tell Python that if there is content in Column A, write the content in Column B, and so on and so forth because I want to write to the same file week over week. Here is what I have so far.

content = [1, 2, 3]
csvfile = "my/file/path"
column = zip(content)
with open(csvfile, 'a') as output:
    writer = csv.writer(output, dialect = "excel")
    for item in content:
        writer.writerow(item)

When I run this twice, my content is appended to the bottom of the column and not a new column. Is my error in my specified mode? W truncates and R is only for reading so I am at a loss.

Here is how it looks when run twice:

Column A
1
2
3
1
2
3
content = [1, 2, 3]
csvfile = "my/file/path"
existing = list(csv.reader(open(csvfile))) if os.path.exists(csvfile) else []
#first you have to read in your existing rows/cols
cols = zip(*existing)
#then you transpose it to get your columns
cols.append(content) #add your new content


with open(csvfile, 'w') as output:
    writer = csv.writer(output, dialect = "excel")
    for item in zip(*cols): #change columns back to rows
        writer.writerow(item)

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