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

时间:2014-07-01 21:50:18

标签: python csv

每周一周,我希望能够将我拥有的列表中的内容写入CSV文件。基本上,我需要找到一种方法告诉Python,如果列A中有内容,请在B列中写入内容,依此类推,因为我想在一周内写入同一个文件。这是我到目前为止所拥有的。

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)

当我运行两次时,我的内容会附加到列的底部而不是新列。我的错误是在我指定的模式下吗? W truncates和R仅用于阅读,所以我很茫然。

以下是两次运行时的外观:

Column A
1
2
3
1
2
3

1 个答案:

答案 0 :(得分:1)

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)