简体   繁体   English

如何将列表写入CSV文件中的特定位置?

[英]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. 一周又一周,我希望能够将列表中的内容写入CSV文件。 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. 本质上,我需要找到一种方法告诉Python如果A列中有内容,将内容写在B列中,依此类推等等,因为我想每周写一次相同的文件。 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. W截断而R仅用于阅读,所以我很茫然。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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