新的專欄中,我想一個新列添加到現有的文件。但是它增加了一些額外的循環。蟒蛇寫入到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
該腳本工作正常,我在Mac上? – vinod
IM使用python 2.7和在Mac – jxn