LoginSignup
19
25

More than 3 years have passed since last update.

【Python】Pythonでcsvファイルに書き込み

Last updated at Posted at 2020-01-05

はじめに

csvファイルを書き込むためのPythonコードです。
ディレクトリの指定とファイル名を日付と時間にするなど
ファイル名に日時時間情報を付けることで実行された際に一意の名前のファイルができるため、ログの保存に便利です。

環境

  • Windows 10
  • Python3.7
  • csv(もとからはいってるので特にインストールは不要)
  • datetime(もとからはいってるので特にインストールは不要)

コード

csv_log.pyと同じディレクトリのoutputディレクトリにcsv出力します。

csv_log.py
import datetime
import csv

# 日時の取得
now = datetime.datetime.now()
# ディレクトリの指定はここ
filename = './output/log_' + now.strftime('%Y%m%d_%H%M%S') + '.csv'

# ファイル,1行目(カラム)の作成
with open(filename, 'w') as f:
    writer = csv.writer(f)
    writer.writerow(['time','x','y','z'])

x,y,z = 0,0,0
while(1):
    # なんらかの処理を書く
    x += 1
    y += 2
    z += 3
    now_str = datetime.datetime.now().strftime('%H:%M:%S.%f')

    # filenameを作成したファイル名に合わせる
    # writer.writerowでlistをcsvに書き込む
    with open(filename, 'a', newline="") as f:
        writer = csv.writer(f)
        writer.writerow([now_str, x, y, z])

    # 処理が終わったらbreak
    break

こんな感じのcsvができると思います

time x y z
2021/1/1 12:00:00.000... 1 2 3
2021/1/1 12:00:01.000... 4 5 6
: : : :

おわりに

今回は以上ですが、pandasを使ってデータ分析などを行うことが多く、
pandasでも簡単にcsv出力できるのでまた更新しようと思います。
ありがとうございました!

19
25
2

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
19
25