python - 写一个csv文件python

标签 python excel csv

所以我有一个列表:

>>> 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])

但是当我打开创建的 csv 文件时,出现一个窗口要求我选择分隔符 无论如何,我有类似的东西 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)

重点是,每一行都必须是一个序列;实际上,每一行只是一个字符串。

那么,为什么您得到的是 R,e,f,e,r,e,n,c,e,... 而不是错误?好吧,字符串是一个字符序列(每个字符本身就是一个字符串)。因此,如果您尝试将 "Reference" 视为一个序列,它与 ['R', 'e', 'f', 'e', 'r', ' e', 'n', 'c', 'e'].


在评论中,你问:

Now what if I want to write something in the second column ?

好吧,那么每一行都必须是两个项目的列表。例如,假设您有这个:

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)

关键是,找到一种方法来创建 listlist——如果你不能在脑海中全部弄清楚,你可以 打印所有中间步骤以查看它们的外观——然后您可以调用writerows。如果您只能弄清楚如何一次创建每一行,请使用循环并在每一行上调用 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))

关于python - 写一个csv文件python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14725877/

相关文章:

python - Web2py - 尝试从没有 'for' 句子的 rows 对象获取值

python - "PortMidi: ` 关闭 mido 端口时错误指针 '"

vba - 正确的 `If Condition` 以及在 Excel-VBA 中正确使用 `Loop Structure`

excel - 新问题 - 运行时错误 - 内存不足

linux - 将 ctrl 分隔文件转换为 csv

python - 如何加载图像并将其转换为适合 PyTorch 的张量?

python - 为什么信号不简单地称为事件?

excel - 如何判断单元格是否存在于另一个 Google 表格上

python - 为什么从 WAV 文件导出的 CSV 文件比原始 WAV 文件大得多?

python - Numpy 数组到 CSV 的 Python 列表?