LoginSignup
0
1

More than 1 year has passed since last update.

CSV書き出し方法

Last updated at Posted at 2021-07-14

<方法1:pandasを使う(逐次処理版)>
メリット:dataframeに格納してから、一気に書き出すので、dataframeで平均や合計などのデータ操作がしやい。

(FOR文に対応しやすい書き方)
   csv_file_path = "C:\temp\csv.csv"
   code = []
   timestamp = []
   benefit_today = []
   fieldnames = ['code', 'timestamp', 'benefit_today']

   # データを追加
   code.append(stock_code)
   timestamp.append(time)
   benefit_today.append(benefit)

   df = pd.DataFrame(data={'code': code,
                           'timestamp': timestamp,
                           'benefit_today': benefit_today}, columns=fieldnames)

   # df.to_csv(csv_file_path, index=False, encoding='utf8')  # 上書きモード
   df.to_csv(csv_file_path, index=False, mode='a', encoding='utf8')  # 追記モード

<方法2:csvパッケージを使う>

import csv

with open(csv_file_path, 'w', newline="") as csv_file:
    # header を設定
    fieldnames = ['code', 'timestamp', 'benefit_today', 'benefit_subtotal', 'open1', 'low1', 
                  'high1','close1', 'volume1', 'open2', 'low2', 'high2', 'close2', 'volume2']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()

    # データの書き込み
    writer.writerow({'code': stock_code,
                         'timestamp': str(time),
                         'benefit_today': benefit_today,
                         'benefit_subtotal': benefit_subtotal,
                         'open1': row1['open'],
                         'low1': row1['low'],
                         'high1': row1['high'],
                         'close1': row1['close'],
                         'volume1': row1['volume'],
                         'open2': row2['open'],
                         'low2': row2['low'],
                         'high2': row2['high'],
                         'close2': row2['close'],
                         'volume2': row2['volume']})

       
引数newline="" は改行コードをNullに指定することで、空行の出力を防ぐ。
追記にしたい場合、引数にmode="a"を追加。

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