windowsでpythonを実行中、csvファイルを作成していてなんだろうこのもじれつや改行は...?と思ったので備忘メモ
読み取ったcsvファイルのヘッダーに\ufeffという文字列が追加されてしまっていたので、読み取るときのエンコーディングを指定する.
import csv
with open(csv_path, 'r', enconding='UTF-8-sig') as r_obj:
reader = csv.DictReader(r_obj)
書き込むときは、改行コードをブランクになるように指定する
with open(write_csv_path, 'w', encoding='UTF-8', newline='') as w_obj:
fields = ['ID', 'BUILD_TYPE']
writer = csv.DictWriter(w_obj, fieldname=fields)
writer.writeheader()
まとめ
import csv
read_csv_path = r'.\Python\android_version_cookbook.csv'
write_csv_path = r'.\Python\new_android_version_cookbook.csv'
_tmp = []
with open(read_csv_path, 'r', encoding='UTF-8-sig') as r_obj:
csvreader = csv.DictReader(r_obj)
for line in csvreader:
for i in range(1, 5):
d = {}
d['ID'] = line['ID']
d['POSITION_ID'] = line['POSITION_ID']
d['GSI_CODE'] = f'0{i}'
d['RELEASE_DATE'] = line['RELEASE_DATE']
d['BUILD_TYPE'] = line['BUILD_TYPE']
d['VALUE'] = line['VALUE']
d['NAME'] = line['NAME']
_tmp.append(d)
with open(write_csv_path, 'w+', encoding='UTF-8', newline='') as w_obj:
fields = ['ID',
'POSITION_ID',
'GSI_CODE',
'RELEASE_DATE',
'BUILD_TYPE',
'VALUE',
'NAME']
writer = csv.DictWriter(w_obj, fieldnames=fields)
writer.writeheader()
for row in _tmp:
writer.writerow(row)