2017-05-25 6 views
0

私は初心者で、csvファイルに以下のデータがあり、 'account_key'を 'acct'に変更したいと思います。私はそれをどうやってやるべきですか?Python(2.7)でcsvファイルのタイトルを変更するには?

account_key、ステータス、join_date、CANCEL_DATE、days_to_cancel、キャンセル、
448をis_canceled、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

ありがとう!それは魅力のように働いた! –

関連する問題