python 檔案和異常處理__python

來源:互聯網
上載者:User
#10-1 python學習筆記
with open("learnpy.txt") as file_pro:    contents = file_pro.read()    print(contents)with open("learnpy.txt") as file_pro:    for line in file_pro:        print(line)with open("learnpy.txt") as file_pro:    lines = file_pro.readlines()for line in lines:    print(line)

#10-2 replace python with c
for line in lines:    print(line.replace('Python','c'))

#10-3 寫入檔案
print("please input your name")user_name = input()with open("guest.txt",'w') as file_ob:    file_ob.write(user_name)

#10-4 向檔案中添加使用者
while True:    message = input("please input your name")    if(message == 'quit'):        break    print("hello"+" "+message)    with open('guest_list.txt', 'a') as file_object:        file_object.write(message+'\n')

#10-7 加法計算機
print("Give me two numbers, and I'll add them.")print("Enter 'q' to quit.")while True:    first_number = input("\nFirst number: ")    if first_number == 'q':        break    second_number = input("Second number: ")    try:        answer = int(first_number) + int(second_number)    except ValueError:        print("illegal input")    else:        print(answer)


#10-8 貓和狗
def printFile(file_name):    try:        with open(file_name) as file_ob:            print(file_ob.read())    except FileNotFoundError:          msg = file_name + " does not exist."          print(msg)printFile("cats.txt")printFile("dogs.txt")printFile("cat.txt")

#10-9 貓和狗,檔案不存在程式沉默
def printFile2(file_name):    try:        with open(file_name) as file_ob:            print(file_ob.read())    except FileNotFoundError:          passprintFile2("cats.txt")printFile2("dogs.txt")printFile2("cat.txt")

#10-11 喜歡的數字 import json
love = input("input your luck number")with open("json.txt",'w') as file_ob:    json.dump(love,file_ob)with open("json.txt") as file_ob:    print("you love number "+ json.load(file_ob))



   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.