Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
1

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 3 years have passed since last update.

【Python】csv・txtファイルの行データを読み込み、リストに1次元配列として格納する

Last updated at Posted at 2020-11-28

csv・txtファイルの行データを読み込み、リストに格納する.gif

読み込んだ行データをリストに格納する作業がよくあったので、関数化して実装していきたいと思います。

実装

Python 3.7.6

  • txtファイル
txt
Apple
Grape
Orange
Melon
Peach
  • CSVファイル

引数にtxtかcsvのfileパスを指定すると、読み込んだデータをリストとして返します。

import csv 
import itertools # 2次元配列=>1次元配列にするため


TEXT_FILE = 'sample.txt'
CSV_FILE = 'sample.csv'

def read_txtfile_as_list(filePath=None):
    """ 
    テキストファイルを読み込み、リストとして返します。

    Parameters
    ----------
    filePath : str

    Returns
    -------
    item_list : list of str
    """
    with open(filePath, 'r') as f:
        text_data = [line.strip() for line in f]
    return text_data

def read_csvfie_as_list(filePath=None):
    """ 
    CSVファイルを読み込み、リストとして返します。

    Parameters
    ----------
    filePath : str 

    Returns
    -------
    item_list : list of str
    """
    with open(filePath, 'r') as f:
        csv_data =  [line for line in csv.reader(f)]
    # return sum(csv_data, []) 簡易的な書き方 こっちだと処理が遅い
    return list(itertools.chain.from_iterable(csv_data))

def read_file_as_list(filePath=None):
    """ 
    テキストファイルかCSVファイルを読み込み、リストとして返します。

    Parameters
    ----------
    filePath : str

    Returns
    -------
    item_list : list of str
    """
    if filePath[-4:] == '.txt':
        with open(filePath, 'r') as f:
            text_data = [line.strip() for line in f]
        return text_data
    elif filePath[-4:] == '.csv':
        with open(filePath, 'r') as f:
            csv_data =  [line for line in csv.reader(f)]
            return list(itertools.chain.from_iterable(csv_data))
    else:
        return None


# テキストファイルの中身を表示
text_samp1 = read_txtfile_as_list(TEXT_FILE)
print(text_samp1)

# OUTPUT: ['Apple', 'Grape', 'Orange', 'Melon', 'Peach']

# CSVファイルの中身を表示
csv_samp1 = read_csvfie_as_list(CSV_FILE)
print(csv_samp1)

# OUTPUT: ['dog', 'cat', 'cow', 'fox', 'monkey']

# テキスト・CSVファイルの中身を表示
text_samp2 = read_file_as_list(TEXT_FILE)
csv_samp2 = read_file_as_list(CSV_FILE)

print(text_samp2)
print(csv_samp2)

# OUTPUT: ['Apple', 'Grape', 'Orange', 'Melon', 'Peach']
# OUTPUT: ['dog', 'cat', 'cow', 'fox', 'monkey']

書いている途中で行データだけを読み込むのであれば、標準のreadlinesメソッドで読み込めるので、csvライブラリをインポートする必要性はなかったなーと思ったのですが、今後、csvファイルの中身をリストにする機会があるかもしれないと思ったので、一応、残しておきます。

0
1
5

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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?