0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

備忘メモ: csvファイルの一部を更新したいときに見る

Last updated at Posted at 2024-06-17

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)


参考:
https://qiita.com/Ryo-0131/items/7d6b1c772b32c3bbe15e

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?