2014-07-01 301 views
0

一周以上,我希望能够从一个列表中写入我有一个CSV文件的内容。从本质上讲,我需要找到一种方法来告诉Python,如果列A中有内容,请将列中的内容写入列B,等等,因为我想在一周内写入同一个文件周。这是我到目前为止。如何将列表写入CSV文件中的特定位置?

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截断和R仅用于阅读,所以我很茫然。

这里是如何看起来运行两次时:

Column A 
1 
2 
3 
1 
2 
3 
+0

您需要阅读现有的文件,在第二列中插入您的数据,然后写在文件。 csv.writer就像你告诉它的那样追加。 –

回答

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) 
相关问题