0
0

More than 3 years have passed since last update.

【Python】CSVに行を足してよいかどうか(新しい値があるかどうか)判断する関数

Last updated at Posted at 2021-09-07

先程書いたものとはTFが逆で戻るようになってます。

def ok_to_add_data(csv_file:str, data:list) -> bool:
    '''
    Returns
    -------
    True when the data has new value.
    False when the data has no new value like;
    - last_line == data,
    - data has missing values and other data is same as values of same index of last_line
    '''
    # CSV読み込み
    with open(csv_file, 'r', encoding='utf8') as f:
        rows = [row for row in csv.reader(f)]
    try:
        last_line = rows[-1]
        # 最後が空白行の場合があるのでケア
        if last_line == []:
            last_line = rows[-2]
        # 全く同じデータであればNG
        if(last_line == data):
            return False
        for csv_cell, data_cell in zip(last_line, data):
            # 異なるデータ
            if csv_cell != data_cell:
                # 欠測値でないなら追記と判断
                if data_cell:
                    return True
        # 差分が欠測値のみであればNG
        return False
    # おかしい場合はとりあえず追記
    except IndexError:
        return True
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