编写一个csv文件python
所以我有一个列表:
>>> print references >>> ['Reference xxx-xxx-xxx-007 ', 'Reference xxx-xxx-xxx-001 ', 'Reference xxx-xxx-xxxx-00-398 ', 'Reference xxx-xxx-xxxx-00-399']
(名单比这个长得多)
我需要写一个CSV文件,看起来如下:
Column 1: Reference xxx-xxx-xxx-007 Reference xxx-xxx-xxx-001 [...]
我试过这个:
c = csv.writer(open("file.csv", 'w')) for item in references: c.writerows(item) Or: for i in range(0,len(references)): c.writerow(references[i])
但是当我打开创build的csv文件,我得到一个窗口要求我select分隔符无论如何,我有一些像R,E,F,E,R,E,N,C,ES
writerows
需要一系列的行,每一行都是一系列的列,然后写出来。
但是你只有一个值list
。 所以你要:
for item in references: c.writerow([item])
或者,如果你想要一个单行的话:
c.writerows([item] for item in references)
重点是,每一行都必须是一个序列; 因为它是每行只是一个单一的string。
那么,你为什么得到R,e,f,e,r,e,n,c,e,…
而不是错误? 那么,一个string是一个字符序列(每个字符本身就是一个string)。 所以,如果你试图把"Reference"
当作一个序列来对待,那么就和['R', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e']
。
在一个评论中,你问:
现在,如果我想在第二栏写东西呢?
那么,每一行都必须是两个项目的list
。 例如,假设你有这个:
references = ['Reference xxx-xxx-xxx-007 ', 'Reference xxx-xxx-xxx-001 '] descriptions = ['shiny thingy', 'dull thingy']
你可以这样做:
csv.writerows(zip(references, descriptions))
或者,如果你有这个:
references = ['Reference xxx-xxx-xxx-007 ', 'Reference xxx-xxx-xxx-001 ', 'Reference xxx-xxx-xxx-001 '] descriptions = {'Reference xxx-xxx-xxx-007 ': 'shiny thingy', 'Reference xxx-xxx-xxx-001 ': 'dull thingy']}
你可以这样做:
csv.writerows((reference, descriptions[reference]) for reference in references)
关键是,find一个方法来创buildlist
s – 如果你不能把它全部弄清楚,你可以print
所有的中间步骤,看看它们是什么样的,然后你可以调用writerows
。 如果只能弄清楚如何一次创build一行, writerow
在每行上使用一个循环并调用writerow
。
但是如果你得到第一列值,然后再获得第二列值呢?
那么,你不能添加一列到CSV; 你只能按行来写,而不能按列来写。 但是有一些方法。
首先,您可以按转置顺序编写表格:
c.writerow(references) c.writerow(descriptions)
然后,将其导入Excel后,只需将其转回。
其次,不要像你得到的那样写下价值观,而要把它们汇总成一个清单,最后写下所有的东西。 像这样的东西:
rows=[[item] for item in references] # now rows is a 1-column table # ... later for i, description in enumerate(descriptions): values[i].append(description) # and now rows is a 2-column table c.writerows(rows)
如果最糟糕的是,你可以随时写CSV,然后读回来,写一个新的添加列:
with open('temp.csv', 'w') as temp: writer=csv.writer(temp) # write out the references # later with open('temp.csv') as temp, open('real.csv', 'w') as f: reader=csv.reader(temp) writer=csv.writer(f) writer.writerows(row + [description] for (row, description) in zip(reader, descriptions))
writerow
将不同列中的元素写入一个迭代器。 这意味着如果你提供了一个元组,每个元素将在一列中。 如果您提供一个string,每个字母将在一列中。 如果您希望同一列中的所有内容执行以下操作:
c = csv.writer(open("file.csv", 'wb')) c.writerows(references)
要么
for item in references: c.writerow(references)
c = csv.writer(open("file.csv", 'w')) c.writerows(["Reference"]) # cat file.csv R,e,f,e,r,e,n,c,e
但
c = csv.writer(open("file.csv", 'w')) c.writerow(["Reference"]) # cat file.csv Reference
会像其他人所说的那样工作。
由于writerow
和writerows
混淆,我的原始答案是有缺陷的。