1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【コピペでOK!】PythonでCSVファイルへの読み込み、書き込み

Last updated at Posted at 2019-08-27

tl;dr

PythonでCSVファイルを読み書きする方法をまとめます。

用意するもの・環境

  • macOS Mojave 10.14.6
  • Python 3.7(ANACONDA3)
  • PyCharm 2019.2

開発環境の構築は下記の記事を参考にしてください。

【これさえ読めばOK】MacでPythonを使って開発するための準備
https://qiita.com/ryoichiro001/items/35a232a430c41dd512fa

公式ドキュメント

CSV ファイルの読み書き
https://docs.python.org/ja/3/library/csv.html

パラメータの詳細はこちらを参照してください。

CSVパッケージを使用する


import csv

CSVファイルの読み込み


import csv
import os


def get_info_from_csv(dir_name, file_name, delimiter=','):
    p_file = os.path.join(dir_name, file_name)

    with open(p_file, 'r', encoding='utf-8') as f:
        reader = csv.reader(f, delimiter=delimiter)
        lists = [row for row in reader]
        return lists

この例ではencodingをutf-8にしているが、これは読み込む対象のファイルに合わせる必要がある。


# 呼び出し例
url_list = get_info_from_csv('inputs_files', 'input.txt')

CSVファイルの書き込み


import csv
import os


def put_info_to_csv(lists, dir_name, file_name, header=[], delimiter=','):
    """二次元配列をCSVファイルに出力
    :param lists:出力したい二次元配列
    :param dir_name:ディレクトリ名(1階層下を想定)
    :param file_name:ファイル名
    :param header:ファイルのヘッダ
    :param delimiter:CSVの区切り文字
    :return:なし
    """
    p_file = os.path.join(dir_name, file_name)

    with open(p_file, "w", encoding='utf-8') as f:
        writer = csv.writer(f, delimiter=delimiter, quoting=csv.QUOTE_MINIMAL)

        if header:
            writer.writerow(header)

        writer.writerows(lists)

# 呼び出し例
out_info = [[]]
out_info.clear() # 2次元配列を初期化

count = 1

out_line = []
out_line.append(count)
out_line.append('A')
out_info.append(out_line)                        

count += 1

out_line = []
out_line.append(count)
out_line.append('B')
out_info.append(out_line)                        

count += 1

out_line = []
out_line.append(count)
out_line.append('C')
out_info.append(out_line)                        

put_info_to_csv(out_info, 'temporary_files', 'output.txt')
output.txt
1,A
2,B
3,C

参考URL

PythonでCSVファイルを読み込み・書き込み(入力・出力)
https://note.nkmk.me/python-csv-reader-writer/

Pythonで2次元配列の静的確保と動的確保
http://sonickun.hatenablog.com/category/%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0?page=1402667101

Pythonでリスト(配列)の要素を削除するclear, pop, remove, del
https://note.nkmk.me/python-list-clear-pop-remove-del/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?