日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python--从入门到实践--chapter 10 文件及错误

發布時間:2024/7/5 python 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python--从入门到实践--chapter 10 文件及错误 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文件的讀寫:

with open(filename, 'a', encoding='utf-8') as file:

with :后面不必寫close文件
第二個參數:‘a’ 追加;‘w’ 寫;‘r’ 讀
encoding = ‘utf-8’ 編碼格式,中文的話一般寫上

enter = 'y' while enter == 'y':name = input("請輸入你的名字:")filename = "guest_record.txt"if name != "":with open(filename, 'a', encoding='utf-8') as file:file.write(name + '\n')print("hello, ", name, " !")conti = 'y'while conti == 'y':reason = input("你為什么喜歡python?")with open(filename, 'a', encoding='utf-8') as file:file.write(reason + '\n')conti = input("繼續輸入原因嗎?y/n ")enter = input("繼續訪問嗎?y/n ")

file.readlines() 文件按行讀取存在列表內
file.read() 整體讀取

filename = 'pi_digits.txt' with open(filename) as pi_file: #with幫助我們適時關閉文件lines = pi_file.readlines() #把文件按行存儲 pi_str = '' for line in lines:pi_str += line.strip() #strip()行左右的空刪除 print(pi_str[:7]+"...") print(len(pi_str)) birthday = input("輸入你的生日:yyyymmdd ") if birthday in pi_str:print("你的生日出現在pi中。") else:print("你的生日不在pi中。") filename = 'learning_python.txt' with open(filename) as file:'''方法1:整個文件一次讀取'''# print(file.read())'''方法2:分行讀取'''# for line in file.readlines():# print(line.strip())'''方法3'''line1 = file.readlines()for l in line1:print(l.replace("Python", "C++").strip())

try;except;else(try代碼塊出錯后,執行except部分,未出錯,執行else)
錯誤處理可以使程序不至于崩潰,還可以繼續運行

print("input 2 numbers to divide, enter 'q' to quit.") while True:first = input("\nfirst num: ")if first == 'q':breaksecond = input("\nsecond num: ")try:answer = int(first) / int(second)except ZeroDivisionError:print("divide zero!!!")else:print(answer)breakfilename = 'learning_python.txt' try:with open(filename) as f_obj:contents = f_obj.read() except FileNotFoundError:msg = "Sorry, the file " + filename + " does not exist."print(msg)# pass #一言不發,跳過 else:words = contents.split()print("the title ", filename, " has ", str(len(words)), " words.")while True:print("input 2 nums : ")try:a = int(input('first num: '))except ValueError:print("請輸入數字!")continuetry:b = int(input('second num: '))except ValueError:print("請輸入數字!")continueprint("sum of two nums is ", a+b)

json文件存儲

json.dump(object, file) json.load(file) import json numbers = [2, 3, 5, 7, 11, 13] filename = "numbers.json" with open(filename,'w') as file:json.dump(numbers,file)with open(filename) as file:numbers = json.load(file) print(numbers)def get_stored_username():filename = "username.json"try:with open(filename) as file:username = json.load(file)except FileNotFoundError:return Noneelse:return usernamedef get_new_username():username = input("What is your name? ")filename = "username.json"with open(filename, 'a') as file:json.dump(username, file)return usernamedef greet_user():username = get_stored_username()if username:print("Welcome back, ", username, " !")else:get_new_username()print("We'll remember you when you come back, ", username, " !")greet_user() import json def get_num():try:global favor_numfavor_num = int(input("輸入你喜歡的數字:"))except ValueError:print("你輸入的不是數字,請重新輸入!")get_num()return favor_numdef store_num(num):filename = "user_favor_num.json"with open(filename, 'a') as file:json.dump(num, file)def getAndStore():store_num(get_num())def print_num():filename = "user_favor_num.json"try:with open(filename) as file:num = json.load(file)except FileNotFoundError:getAndStore()else:print("i know your favorite number! it is ", num)print_num() 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的python--从入门到实践--chapter 10 文件及错误的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。