[英]how to copy some csv file colums into another csv file with python?
I have a 10 columns csv file and i would like to copy the first, the third and the seventh or another set of columns into a new csv file. 我有一个10列的csv文件,我想将第一,第三和第七个或另一组列复制到一个新的csv文件中。 Can you help me?
你能帮助我吗? I have this code but i can't transform it to have my need.
我有这段代码,但是我无法将其转换为我的需要。
<code>
def selection( fr=sys.stdin, fw=sys.stdout, delim=';'):
my_reader = csv.reader(fr, delimiter=delim)
my_writer = csv.writer(fw, delimiter=delim)
to_write = [ col for col in zip(*my_reader) if col[0] == 'Nb_doc' ]
my_writer.writerows(zip(*to_write))
return
</code>
this code copy only the column named 'nb_doc'. 此代码仅复制名为“ nb_doc”的列。
Maybe you could have a list of field names you'd like to select from and check if the first element of the column is in there: 也许您可以从中选择一个字段名称列表,然后检查该列的第一个元素是否在其中:
fields = ["Nb_doc", "SomeOtherField1", "SomeOtherField2"]
Then, your list comprehension probably just needs to look like this: 然后,您的列表理解可能只需要看起来像这样:
to_write = [ col for col in zip(*my_reader) if col[0] in fields ]
The following will copy just the first, third, and seventh columns: 下面将仅复制第一,第三和第七列:
colNums = [0, 2, 6]
to_write = [ col for i, col in enumerate(zip(*my_reader)) if i in colNums ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.