Help us understand the problem. What is going on with this article?

[Python] csvファイルの区切り文字をタブ区切りに変換

やりたいこと

  • csvファイルの区切り文字をタブ区切りに変換したい
  • ファイル中に住所等、カンマが含まれている場合にタブ区切りにした方が後続処理(例えばDBに取り込む等)がしやすくなる

ポイント

- csvモジュールをimportして使うと簡単

呼び出し側のプログラムの方でcsvモジュールをimport

  • defのファイルの最初でcsvモジュールをimport
  • with openで対象ファイルの読み書きを行う
  • 対象ファイルをカンマ区切りで読み込んで、タブく区切りで書き出す  → 対象ファイルに上書きされる
  • csv.readerを使って読み込んだら、行単位で配列に格納する
  • 書き込みは↑で読み込んだ配列をwriter.writerrows(配列名)で一気に書き出す  1行づつ書き込みたい時はwriter.writerrow(行列)で書き出せる
convertTav.py
def CsvToTsv(path):

    #読み込み用配列
    line = []

    #読み込み
    with open(path, "r", newline="") as f:
            #読み込みオブジェクト作成(カンマ区切り)
            reader = csv.reader(f, delimiter = ",")
            #読み込み
            line = [row for row in reader]
    #close
    f.close

    #書き込み
    with open(path, "w", newline="") as f:
            #書き込みオブジェクト作成(タブ区切り)
            writer = csv.writer(f, delimiter = "\t")
            #まとめて書き込み
            writer.writerows(line)
    #close
    f.close

追記

読み込みと書き込みでencodeを変換したい場合はopen時にencodingを指定する
(例)読み込み時 Shift-jis, 書き込み時 utf-8

convertTav.py
#読み込み
with open(path, "r", newline="", encoding="cp932") as f:

#書き込み
with open(path, "w", newline="", encoding="utf_8") as f:

Shift-jisではうまくいかず、cp932を指定することでうまくいった

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした