Exercise 1:
file = open("a.txt","w")
#file.write("hello")
s = ["hello\n","world"]
file.writelines(s)
file.close()
Exercise 2:
'''try:
file = open("a.txt","w")
#file.write("hello")
s = ["hello\n","world"]
file.writelines(s)
except BaseException as e:
print(e)
finally:
file.close()'''
with open("a.txt","w") as file:
file.write("hello")
Exercise 3:
with open("b.txt","r") as file:
r1 = file.read()
print(r1)
Exercise 4:
with open("c.txt","r") as file:
while True:
r1 = file.readline()
if not r1:
break
else:
print(r1,end = "")
with open("c.txt","r") as file:
list01 = file.readlines()
for item in list01:
print(item,end = "")
Exercise 5:
with open('cktn.jpg', 'rb') as f:
with open('cktn_copy.jpg', 'wb') as w:
for line in f.readlines():
w.write(line)
print('Image duplicated successfully!')
Homework:
import easygui as g
card_money = []
with open("card_money.txt","r") as file:
card_money = file.readlines()
card1_num = "1001"
card1_pwd = "123456"
card1_money = int(card_money[0])
card2_num = "1002"
card2_pwd = "234567"
card2_money = int(card_money[1])
times = 0
while True:
card = g.multpasswordbox("Please input card number and pin code",title = "Banking System",fields = ("Card Number","pin code"))
money = 0
flag = 0
if card == [card1_num,card1_pwd]:
money = card1_money
flag = 1
g.msgbox("Login Successfully",title = "Banking System")
elif card == [card2_num,card2_pwd]:
flag = 2
money = card2_money
g.msgbox("Login Successfully",title = "Banking System")
else:
times += 1
if times == 3:
g.msgbox("You have input wrong for 3 times. Please contact with bank admin.",title = "Banking System")
pwd = ""
while pwd != "888888":
pwd = g.passwordbox("Please input Admin's password.",title = "Banking System")
times = 0
else:
g.msgbox("Login failed. Please re-input.",title = "Banking System")
continue
while True:
operation = g.buttonbox("Please pick your operation.",title = "Banking System", choices=("Deposit", "Withdraw", "Balance", "Quit"))
if operation == "Quit":
times = 0
if flag == 1:
card1_money = money
elif flag == 2:
card2_money = money
with open("card_money.txt","w") as file:
file.writelines(str(card1_money)+"\n"+str(card2_money))
break
elif operation == "Deposit":
save_money = g.integerbox("Please input money deposit:",title = "Banking System", lowerbound=0, upperbound=1000000)
money = money + save_money
g.msgbox("Operation succeeds. Money deposit is " + str(save_money),title = "Banking System")
elif operation == "Withdraw":
get_money = g.integerbox("Please input money withdrew:",title = "Banking System", lowerbound=0, upperbound=1000000)
if get_money > money:
g.msgbox("Sorry, not enough money. Please re-try",title = "Banking System")
else:
money = money - get_money
g.msgbox("Operation succeeds. Money withdrew is " + str(get_money),title = "Banking System")
elif operation == "Balance":
g.msgbox("Your balance is " + str(money),title = "Banking System")