2017-05-25 37 views
0

我是初学者,在csv文件中有以下数据,我想将'account_key'更改为'acct'。我应该怎么做呢?如何更改python(2.7)中的csv文件的标题?

account_key,地位,join_date,CANCEL_DATE,days_to_cancel,is_canceled
448,取消2014-11-10,2015-01-14,65,真
448,取消,2014-11-05,2014- 11-10,5,真
...
...
...

回答

1

如果文件足够小,以适应到主存储器:

import csv 

with open('path/to/file') as infile: 
    data = list(csv.reader(infile)) 
data[0][0] = 'acct' 

with open('path/to/file', 'w') as fout: 
    outfile = csv.writer(fout) 
    outfile.writerows(data) 

如果文件过大t o适合主内存:

with open('path/to/file') as fin, open('path/to/output', 'w') as fout: 
    infile = csv.reader(fin) 
    header = next(infile) 
    header[0] = 'acct' 
    outfile.writerow(header) 
    for row in infile: 
     outfile.writerow(row) 
+0

谢谢!它像一个魅力一样工作! –