2015-10-15 136 views
0

新的专栏中,我想一个新列添加到现有的文件。但是它增加了一些额外的循环。蟒蛇写入到csv文件

输入文件:

testfile.csv

col1,col2,col3 
1,2,3 
3,4,5 
4,6,7 

输出,我想:

USA_testfile.csv

col1,col2,col3,country 
1,2,3,USA 
3,4,5,USA 
4,6,7,USA 

UK_testfile.csv

col1,col2,col3,country 
1,2,3,UK 
3,4,5,UK 
4,6,7,UK 

这是我曾尝试:

import csv 
import sys 
country_list= ['USA', 'UK'] 

def add_col(csv_file): 
    for country in country_list: 
     with open(csv_file, 'rb') as fin: 
      with open(country+"_timeline_outfile_"+csv_file, 'wb') as fout: 
       writer = csv.writer(fout, lineterminator='\n') 
       reader = csv.reader(fin) 

       all_rows =[] 
       row = next(reader) 
       row.append('country') 
       all_rows.append(row) 
       print all_rows 

       for row in reader: 
        row.append(country) 
        all_rows.append(row) 
       writer.writerows(all_rows) 

add_col(sys.argv[1]) 

这是我得到的错误:

File "write_to_csv.py", line 33, in add_col 
    writer.writerows(all_rows) 
ValueError: I/O operation on closed file 

我试图按照这个帖子here

+0

该脚本工作正常,我在Mac上? – vinod

+0

IM使用python 2.7和在Mac – jxn

回答

-1
import csv 

countries = ['USA', 'UK'] 
data = list(csv.reader(open('testfile.csv', 'rb'))) 

for country in countries: 
    with open('{0}_testfile.csv'.format(country), 'wb') as f: 
     writer = csv.writer(f) 
     for i, row in enumerate(data): 
      if i == 0: 
       row = row + ['country'] 
      else: 
       row = row + [country] 
      writer.writerow(row) 
0

我无法复制你的错误,但我清理了一下你的代码。 没有理由重新打开每种语言的输入文件。

def add_col(csv_file): 
    with open(csv_file, 'rb') as fin: 
     reader = csv.reader(fin) 
     for country in country_list: 
      fin.seek(0) # jump to begin of file again 
      with open(country+"_timeline_outfile_"+csv_file, 'wb') as fout: 
       writer = csv.writer(fout, lineterminator='\n') 
       header = next(reader) 
       header.append('country') 
       writer.writerow(header) 
       for row in reader: 
        row.append(country) 
        writer.writerow(row) 
+0

@Cody布谢Soultion应该更快,但大的csv文件使用时,可能需要大量的内存。 – SleepProgger