LoginSignup
2
6

More than 3 years have passed since last update.

Pythonでcsvに書き込みを行う

Last updated at Posted at 2020-10-27

目的:テキストファイル等に、何かを書き込みたい場合に使用する

# 'w'について
('test.csv', 'w', encoding='utf-8')
表記 概要
r 読み込み
w 新規で書き込み
a 追記で書き込み
r+ 追記の書き込み読み込みファイルが存在しない場合はエラーになる
w+ 新規の書き込みと読み込みファイルがない場合作成
a+ 追記の書き込みと読み込み、ファイルがない場合作成

Hello Worldと書き込みを行う

hello.py

#
with open('test.csv', 'w', encoding='utf-8') as f:
    f.write('Hello World\n')

print('書き込みました。')



-----result------
書き込みました

test.csv
Hellor World

複数の行を出力するときの処理

lang.py

lang = ['SQL',
        'Java',
        'Ruby',
        'PHP',
        'Python']

with open('lang.csv', 'w', encoding = 'utf-8') as f:
    for item in lang:
        f.write(item + '\n')
print('書き込みしました。')

実行結果

lang.csv
SQL
Java
Ruby
PHP
Python

応用 日付の操作

time.py

from datetime import datetime

now = datetime.now()
#print(now) 2020-10-27 19:56:15.019242

str_now = f'{now:%Y/%m/%d %H:%M}'
#print(str_now) 2020/10/27 19:56

with open('time.csv', 'w', encoding='utf-8') as f:
    f.write(str_now + ' - 休日\n')

print('書き込みました。')


実行結果

time.csv

2020/10/27 20:00 - 休日
2
6
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
2
6