简体   繁体   English

编写CSV文件python

[英]Writing a csv file python

So i have a list: 所以我有一个清单:

>>> print references
>>> ['Reference xxx-xxx-xxx-007 ', 'Reference xxx-xxx-xxx-001 ', 'Reference xxx-xxx-xxxx-00-398 ', 'Reference xxx-xxx-xxxx-00-399']

(The list is much longer than that) (列表比这更长)

I need to write a CSV file wich would look this: 我需要编写一个CSV文件,看起来像这样:

Column 1:
Reference xxx-xxx-xxx-007
Reference xxx-xxx-xxx-001
[...]

I tried this : 我尝试了这个:

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

But when I open the csv file created, I get a window asking me to choose the delimiter No matter what, I have something like R,e,f,e,r,e,n,c,es 但是,当我打开创建的csv文件时,出现一个窗口,要求我选择定界符,无论如何,我都有类似R,e,f,e,r,e,n,c,es

writerows takes a sequence of rows, each of which is a sequence of columns, and writes them out. writerows接受一系列的行,每个行都是一个列的序列,并将其写出。

But you only have a single list of values. 但是您只有一个值list So, you want: 所以你要:

for item in references:
    c.writerow([item])

Or, if you want a one-liner: 或者,如果您想要单线:

c.writerows([item] for item in references)

The point is, each row has to be a sequence; 关键是,每一行必须是一个序列; as it is, each row is just a single string. 实际上,每一行只是一个字符串。

So, why are you getting R,e,f,e,r,e,n,c,e,… instead of an error? 那么,为什么要得到R,e,f,e,r,e,n,c,e,…而不是错误? Well, a string is a sequence of characters (each of which is itself a string). 好吧,字符串是一个字符序列(每个字符本身就是一个字符串)。 So, if you try to treat "Reference" as a sequence, it's the same as ['R', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e'] . 因此,如果您尝试将"Reference"视为一个序列,则它与['R', 'e', 'f', 'e', 'r', 'e', 'n', 'c', 'e']


In a comment, you asked: 在评论中,您询问:

Now what if I want to write something in the second column ? 现在,如果我想在第二栏中写些什么?

Well, then each row has to be a list of two items. 好吧,那么每一行都必须是两个项目的list For example, let's say you had this: 例如,假设您有:

references = ['Reference xxx-xxx-xxx-007 ', 'Reference xxx-xxx-xxx-001 ']
descriptions = ['shiny thingy', 'dull thingy']

You could do this: 您可以这样做:

csv.writerows(zip(references, descriptions))

Or, if you had this: 或者,如果您有:

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']}

You could do this: 您可以这样做:

csv.writerows((reference, descriptions[reference]) for reference in references)

The key is, find a way to create that list of list s—if you can't figure it out all in your head, you can print all the intermediate steps to see what they look like—and then you can call writerows . 关键是,找到一种创建list s的方法-如果您无法完全了解list ,则可以print所有中间步骤以查看其外观-然后可以调用writerows If you can only figure out how to create each single row one at a time, use a loop and call writerow on each row. 如果您只能弄清楚如何一次创建每一行,请使用循环并在每一行上调用writerow


But what if you get the first column values, and then later get the second column values? 但是,如果您获得第一列的值,然后又获得第二列的值,该怎么办?

Well, you can't add a column to a CSV; 嗯,您不能将列添加到CSV; you can only write by row, not column by column. 您只能按行写,不能按列写。 But there are a few ways around that. 但是有几种解决方法。

First, you can just write the table in transposed order: 首先,您可以按转置顺序写表:

c.writerow(references)
c.writerow(descriptions)

Then, after you import it into Excel, just transpose it back. 然后,将其导入Excel后,只需将其转置回去即可。

Second, instead of writing the values as you get them, gather them up into a list, and write everything at the end. 其次,与其在获取值时编写值,不如将它们收集到一个列表中,然后将所有内容写在最后。 Something like this: 像这样:

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)

If worst comes to worst, you can always write the CSV, then read it back and write a new one to add the column: 如果情况变得更糟,您始终可以编写CSV,然后将其读回并编写新的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 writes the elements of an iterable in different columns. writerow在不同的列中写入iterable的元素。 This means that if your provide a tuple, each element will go in one column. 这意味着,如果您提供一个元组,则每个元素将进入一列。 If you provide a String, each letter will go in one column. 如果您提供一个字符串,则每个字母都将放在一列中。 If you want all the content in the same column do the following: 如果您希望所有内容都在同一列中,请执行以下操作:

c = csv.writer(open("file.csv", 'wb'))
c.writerows(references)

or 要么

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

but

c = csv.writer(open("file.csv", 'w'))
c.writerow(["Reference"])


# cat file.csv
Reference

Would work as others have said. 会像别人所说的那样工作。

My original answer was flawed due to confusing writerow and writerows . 我最初的答案由于writerowwriterows混乱而存在缺陷。

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

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