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

歡迎訪問 生活随笔!

生活随笔

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

python

Head First Python-Python中与文件相关的操作-读、处理、写

發布時間:2025/3/21 python 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Head First Python-Python中与文件相关的操作-读、处理、写 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近在看head first python,前面也寫了一些筆記,但是基本上沒有涉及到一些完整的代碼,現在將書中的文件相關操作的代碼整理,供以后參考。

主要分為兩大部分,讀取文件、處理異常,處理文件、存儲文件。

0,處理文件

首先介紹后面將會用到的知識點,格式化輸出列表;

如果一個列表嵌套多層列表,使用一般的方法來打印無法打印出嵌套的列表。下面的方法只能打印出一層,如果想打印多層怎么辦?

movies=['aWith a ','bpopulation of 1060', ['cthe village','dis carpeted with ','eazalea blossoms', ['fwith fast-flowing rivers ','gscattered guesthouses','hadding strokes and splashes to ','ithe natural canvas.']]]print(movies) def printList(movies):for i in movies:print(i) print(printList(movies))

下面通過給printList增加參數來控制格式化輸出(intent控制是否需要格式化,t用來控制指標表符個數):

movies=['aWith a ','bpopulation of 1060', ['cthe village','dis carpeted with ','eazalea blossoms', ['fwith fast-flowing rivers ','gscattered guesthouses','hadding strokes and splashes to ','ithe natural canvas.']]]print(movies)#1def printList(movies,intent=False,t=0):for i in movies:if isinstance(i , list): #isinstance檢查一個標識符是否指示某個指定類型的數據對象# for j in i:printList(i,intent,t+1)#增加一層嵌套制表符加1else:if intent:for j in range(t):print("\t", end='')print(i)print(printList(movies,False))#2 print(printList(movies,True,0))#3

輸出如下:

?

?1,讀取文件

pyhont中使用open來打開一個文件:

import os if os.path.exists('./temp/sketch.txt'):data =open('./temp/sketch.txt')print(data.readline(),end='')print(data.readline(),end='')data.seek(0)for each_line in data:if not each_line.find(':') == -1:(role,line_spoken)=each_line.split(':',1)print(role,end='')print(' said: ',end='')print(line_spoken,end='')data.close() else:print('file not exists!!!')

2,處理異常

如果要讀取的文件不存在咋辦?

data =open('./temp/sketch.txt') print(data.readline(),end='') print(data.readline(),end='') data.seek(0) for each_line in data:try:(role,line_spoken)=each_line.split(':',1)print(role,end='')print(' said: ',end='')print(line_spoken,end='')except ValueError:pass data.close()

我們知道,打開一個文件,讀取或者寫入結束后要進行關閉。

3,存儲文件

保存一個文件:

(1)使用print(),print函數的參數file來定義輸出對象,默認輸出到屏幕:

man = [] other = [] try:data=open('./data/sketch.txt')for each_line in data:try:(role,line_spoken)=each_line.split(':',1)line_spoken=line_spoken.strip()if role=='Man':man.append(line_spoken)elif role=='Other Man':other.append(line_spoken)except ValueError:passdata.close() except IOError as err:print("the datafile is missing..."+str(err))try:with open('./temp/man_data.txt','a') as man_data:print(man, file=man_data)with open('./temp/other_data.txt','a') as other_data:print(other, file=other_data) except IOError as err:print ('ERROR: '+str(err))

(2)使用pickle(),pickle函數有存文件dump()和讀文件load()兩個方法,將文件以二進制流的形式存儲到本地:

import pickle import sysdef print_lol(the_list,indent=False,level=0,lol=sys.stdout):for each_item in the_list:if isinstance(each_item,list):print_lol(each_item,indent,level+1,lol)else:if indent:for tab_stop in range(level):print('\t',end='',file=lol)print(each_item,file=lol)man = [] other = [] try:data=open('./data/sketch.txt')for each_line in data:try:(role,line_spoken)=each_line.split(':',1)line_spoken=line_spoken.strip()if role=='Man':man.append(line_spoken)elif role=='Other Man':other.append(line_spoken)except ValueError:passdata.close() except IOError as err:print("the datafile is missing..."+str(err)) #存文件 try:with open('./temp/man_data.dat','wb') as man_data:pickle.dump(man,man_data)with open('./temp/other_data.dat','wb') as other_data:pickle.dump(other,other_data) except pickle.PickleError as err:print ('ERROR: '+str(err)) #讀文件 new_man=[] try:with open('./temp/man_data.dat','rb') as new_man_file:new_man=pickle.load(new_man_file) except IOError as err:print('IOError: '+str(err)) except pickle.PickleError as perr:print('PickError: '+ str(perr))print_lol(new_man) print(new_man[0]) print(new_man[-1])

代碼來源:head first python

轉載于:https://www.cnblogs.com/hoaprox/p/9568935.html

總結

以上是生活随笔為你收集整理的Head First Python-Python中与文件相关的操作-读、处理、写的全部內容,希望文章能夠幫你解決所遇到的問題。

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