LoginSignup
0
1

More than 5 years have passed since last update.

新Python生活六日目【PyQ/9章】

Posted at

学習は終わってはいましたが、
下書き途中にして放置してしまってました><;

ほぼ一ヶ月も。。
PyQからの引き落とし完了通知メールで目が覚めました。

早く吸収して自己学習に切り替えないと!安月給なんだから・・・(お金は大事だよ)

ファイルへの出力

with open('tmp/sample.txt','w',encoding='utf-8') as f: #ファイル名と文字コードの間に'w'を入れる
    f.write('hello, world\n') #ファイルに hello~ を書き込みました

print('書き込み完了')

ループを使って出力してみる

lunch = ['月はカレー' #リストlunchに一週間の昼メニューを設定
         ,'火はうどん'
         ,'水はラーメン'
         ,'木はチャーハン'
         ,'金はうどん']

with open('tmp/sample.txt','w',encoding='utf-8') as f: #出力してくよ
    for menu in lunch: #lunchリストの一個ずつを変数menuに順に代入していくよ
        f.write(lunch + '\n')

print('書き込み完了')
tmp/sample.txtの中身
月はカレー
火はうどん
水はラーメン
木はチャーハン
金はうどん

ループを使って出力してみる②

zaiko = {'赤':5 #zaiko辞書
         ,'青':3
         ,'緑':1
         ,'黄':4
         }

with open('tmp/zaiko.txt','w',encoding='utf-8') as f: #出力してくよ
    for key, value in zaiko.items(): #キー と 値 をzaiko辞書を元に(?)
        f.write(key + 'は' + str(value)) #1行ずつ「キー」と「文字」と「値」を連結して書き込んでくよ
        f.write('\n')
print('書き込み完了')
tmp/zaiko.txtの中身
赤は5
青は3
緑は1
黄は4

日時をファイルに出力(出勤だけの打刻システムを作るよ)

from datetime import datetime #datetimeオブジェクトを利用するよ

now = datetime.now() #変数nowに代入するよ(now:2017-12-18 10:47:44.049200)
str_now = now.strftime('%Y/%m/%d %H:%M') #文字列に変換するよ(str_now:2017/12/18 10:47)

with open('tmp/kinmu.log','a',encoding='utf-8') as f: #出力するよ
    f.write(str_now + ' - 出勤\n') #変換した文字列と連結するよ(yyyy/mm/dd hh:mm - 出勤)
print('書き込み完了')

続き(打刻した時刻によって出勤か退勤かを判断するシステム)

from datetime import datetime #datetimeオブジェクトを利用するよ

now = datetime.now() #変数nowに代入するよ(now:2017-12-18 10:47:44.049200)
str_now = now.strftime('%Y/%m/%d %H:%M') #文字列に変換するよ(str_now:2017/12/18 10:47)

with open('tmp/kinmu.log','a',encoding='utf-8') as f: #出力するよ
    if 6 <= now.hour <14: #打刻した時刻が6-14時なら
        f.write(str_now + ' - 出勤\n') #時刻の後に 出勤 と付ける
    else: #それ以外なら
        f.write(str_now + ' - 退勤\n') #時刻の後に 退勤 と付ける
    print('書き込み完了')
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