From d4eccca9fbfe7c0eb267a013033a988ba54e1d4b Mon Sep 17 00:00:00 2001 From: zhaoqifa Date: Thu, 26 Nov 2015 11:55:31 +0800 Subject: [PATCH] use with to open and close a file --- python/hangover.py | 15 ++++----------- python/smack_my_bitch_up.py | 15 ++++----------- 2 files changed, 8 insertions(+), 22 deletions(-) diff --git a/python/hangover.py b/python/hangover.py index bf923d8..c9b63e1 100755 --- a/python/hangover.py +++ b/python/hangover.py @@ -42,16 +42,9 @@ client.messages.create( ) try: - f = open('logs/file.txt', 'a') -except IOError as e: - # dir & file don't exist; create them - os.mkdir('logs') - f = open('logs/file.txt', 'a') + if not os.path.exists('logs'): + os.mkdir('logs') + with open('logs/file.txt', 'a') as lh: + lh.write("Message sent at " + strftime("%a, %d %b %Y %H:%M:%S") + "\n") except Exception as e: print e -else: - pass - -# log it -f.write("Message sent at " + strftime("%a, %d %b %Y %H:%M:%S") + "\n") -f.close() diff --git a/python/smack_my_bitch_up.py b/python/smack_my_bitch_up.py index 398c881..32b209d 100755 --- a/python/smack_my_bitch_up.py +++ b/python/smack_my_bitch_up.py @@ -43,16 +43,9 @@ client.messages.create( ) try: - f = open('logs/file.txt', 'a') -except IOError as e: - # dir & file don't exist; create them - os.mkdir('logs') - f = open('logs/file.txt', 'a') + if not os.path.exists('logs'): + os.mkdir('logs') + with open('logs/file.txt', 'a') as lh: + lh.write("Message sent at " + strftime("%a, %d %b %Y %H:%M:%S") + "\n") except Exception as e: print e -else: - pass - -# log it -f.write("Message sent at " + strftime("%a, %d %b %Y %H:%M:%S") + "\n") -f.close()