Skip to content

Commit d4eccca

Browse files
author
zhaoqifa
committed
use with to open and close a file
1 parent f9321f0 commit d4eccca

File tree

2 files changed

+8
-22
lines changed

2 files changed

+8
-22
lines changed

python/hangover.py

+4-11
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,9 @@
4242
)
4343

4444
try:
45-
f = open('logs/file.txt', 'a')
46-
except IOError as e:
47-
# dir & file don't exist; create them
48-
os.mkdir('logs')
49-
f = open('logs/file.txt', 'a')
45+
if not os.path.exists('logs'):
46+
os.mkdir('logs')
47+
with open('logs/file.txt', 'a') as lh:
48+
lh.write("Message sent at " + strftime("%a, %d %b %Y %H:%M:%S") + "\n")
5049
except Exception as e:
5150
print e
52-
else:
53-
pass
54-
55-
# log it
56-
f.write("Message sent at " + strftime("%a, %d %b %Y %H:%M:%S") + "\n")
57-
f.close()

python/smack_my_bitch_up.py

+4-11
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,9 @@
4343
)
4444

4545
try:
46-
f = open('logs/file.txt', 'a')
47-
except IOError as e:
48-
# dir & file don't exist; create them
49-
os.mkdir('logs')
50-
f = open('logs/file.txt', 'a')
46+
if not os.path.exists('logs'):
47+
os.mkdir('logs')
48+
with open('logs/file.txt', 'a') as lh:
49+
lh.write("Message sent at " + strftime("%a, %d %b %Y %H:%M:%S") + "\n")
5150
except Exception as e:
5251
print e
53-
else:
54-
pass
55-
56-
# log it
57-
f.write("Message sent at " + strftime("%a, %d %b %Y %H:%M:%S") + "\n")
58-
f.close()

0 commit comments

Comments
 (0)