LoginSignup
0
1

More than 3 years have passed since last update.

Python3でCSVコード変換プログラム

Last updated at Posted at 2019-12-30

Python3でCSVコード変換プログラム

Python3でcsvから対応表を作る
の続き

考え

データ移行などの作業で
コード変換 新旧の対応表を作って順次置換
って作業あるかと思う。

その関数を作ってみた

ソースコード

csv_code_conv.py
#コード変換

import csv

#指定したCSV(2列限定)を順次読み込み。新旧対応表を作る
def getcsvconv(fname:str)->dict:
    with open(fname, encoding="shift_jis") as f:
        reader = csv.reader(f)
        conv_dic = {row[0]:row[1] for row in reader} #リスト内包表記 旧コードをkeyに、新コードをValue
        return conv_dic

#指定されたファイル(CSV)の指定位置のコードを変換する。
def code_conv(fname:str,rownum:int,converter:dict):
    #ファイル名生成
    outfname = fname.replace("exp","imp")
    with open(outfname, "w", newline="",encoding="UTF-8") as f:
        writer = csv.writer(f, delimiter=",", quotechar='"')
        with open(fname, encoding="UTF-8") as f:
            reader = csv.reader(f)
            for row in reader:
                #指定位置をコード変換
                convafterrow = row
                convafterrow[rownum] = converter[row[rownum]]
                writer.writerow(convafterrow)

#本体処理
#コード変換辞書の準備
conv_dic = getcsvconv("対応表.csv")

#変換対象の2次元リスト ファイル名,変換列位置(0スタート)
conv_pre_flist = [
    ["ほにゃらら.csv",2], #
    ["なんちゃら.csv",2],  # 3列目
    #["ごにょごにょ.csv",2], #変換対象外
]

for row in conv_pre_flist:
    code_conv(row[0],row[1],conv_dic)

0
1
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
1