简体   繁体   English

将特定列从CSV文件添加到新的CSV文件

[英]Adding specific column from csv file to new csv file

I am trying to copy few columns from a csv file to a new CSV file. 我正在尝试将几列从csv文件复制到新的CSV文件。 I have written below code to fulfill my requirements. 我已经写了下面的代码来满足我的要求。 But it is not giving me the expected output. 但这并没有给我预期的输出。 Can someone please help me to get the required results.. 有人可以帮我获得所需的结果吗。

import csv

f = csv.reader(open("C:/Users/...../file.csv","rb"))                
f2= csv.writer(open("C:/Users/.../test123.csv","wb"))

for row in f:

      for column in row:

          f2.writerow((column[1],column[2],column[3],column[7]))

f.close()  
f2.close()

The second iteration over each row is not necessary. 不需要在每行上进行第二次迭代。 Just access the columns in that row with the column index. 只需使用列索引访问该行中的列即可。

Also, I don't think there's a close method in csv reader and writer. 另外,我认为csv读取器和写入器中没有close方法。

import csv

f = csv.reader(open("file.csv","rb"))
f2= csv.writer(open("test123.csv","wb"))

for row in f:
    f2.writerow((row[1],row[2],row[3],row[7]))

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

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