国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Python學習系列(五)(文件操作及其字典)

2019-11-14 17:39:47
字體:
來源:轉載
供稿:網友
一、文件操作
1,讀文件
     在以'r'讀模式打開文件以后可以調用read函數一次性將文件內容全部讀出,也可以指定每次read讀多少字節,例如:
1 #coding:utf-82 fn='test1.py'3 fp=open(fn,'r') #以讀的方式打開文件,文件必須首先存在和,.文件在同一目錄下py4 PRint 'reading pos:',fp.tell()5 r=fp.read(20) #讀取文件內容返回字符串6 print 'have read:/"'+r+'/''7 print 'reading pos:',fp.tell()8 print fp.read()9 fp.close()
View Code

2,寫文件

     如果想將某些內容寫入文件,可以以'w'寫的方式打開文件(如果文件不存在會創建),并且清空文件之前的內容。

1 fw='test.txt' 2 fp=open(fw,'w') 3 fp.write('www.google.com') 4 fp.close() 
View Code
3,讀寫文件r+,w+
     二者區別在于:r+是必須針對已存在的文件;w+可以創建未存在的文件。
1  fn='rplus.txt'2  fp=open(fn,'w+') 3  r=fp.read(12) 4  print r 5  fp.close()
View Code
4,追加寫入文件a
   ‘w'寫模式打開的文件只能把內容寫入文件,原有內容將被清除,若想保留,則用‘a'追加寫模式。
 1 fn='rplus.txt' 2 fp=open(fn,'w+') 3 fp.write('aaaaa/n') 4 fp.close() 5   6 fa=open('rplus.txt','a') 7 fa.write('bbbbb/n') 8 fa.close() 9  10 fa=open(fn,'r')11 r=fa.read()12 print r13 fa.close()
View Code

二,格式化讀寫文件

1,格式化寫文件
     調用write函數,使用格式化控制符來格式化寫入字符串。
1 fn='wformat.txt'2 fw=open(fn,'w')3 fw.write('%10s/t %3s/t %6s/n'%('name','age','sex'))4 fw.write('%10s/t %3s/t %6s/n'%('張三',78,'male'))5 fw.write('%10s/t %3s/t %6s/n'%('李四',50,'male'))6 fw.write('%10s/t %3s/t %6s/n'%('王五',80,'male'))7 fw.write('%10s/t %3s/t %6s/n'%('張強',90,'female'))8 fw.close()
View Code
2,讀成列表
     文件的readlines函數可以將文本文件的若干行文本一一映射成列表的若干項,即文本文件的每一行映射成列表的一個數據項,每個數據項都是字符串。
1 fr=open('templist.txt','r')2 print fr.readlines()3 fr.close()
View Code 
結果如下:
1 >>>2 [' aaaaaaaa/n', ' bbbbbbbb/n', ' cccccccc']
View Code
3,讀成一行文件
     調用readline函數讀一行內容,而read函數是一次性將文件的內容全部讀回。另外,可以用strip函數去掉/n和空格。
1 fr=open('templist.txt','r')2 print fr.readline().strip().strip('/n')3 print fr.readline().strip().strip('/n')4 print fr.readline().strip().strip('/n')5 fr.close() 
View Code

結果如下:

1 >>>2 aaaaaaaa3 bbbbbbbb4 cccccccc
View Code
4,split格式化數據
1 fr=open('wformat.txt','r')2 line1=fr.readline()3 print line14 line2=fr.readline()5 print line26 print line2.split('/t')7 fr.close()
View Code

結果如下:

1 >>>2       name     age     sex3  4       張三     78     male5  6 [' /xd5/xc5/xc8/xfd', ' 78', ' male/n']
View Code

讀取文件(格式化)的內容:

 1 fr=open('wformat.txt','r') 2 while (1==1): 3     line=fr.readline() 4     if(line==''): 5         break 6     else: 7         print line 8 fr.close() 9  10 >>> ================================ RESTART ================================11 >>>12       name     age     sex13  14       張三     78     male15  16       李四     50     male17  18       王五     80     male19  20       張強     90     female21  22 >>> 
View Code
5,讀寫子目錄文件
     只需指定文件時描述好路徑即可,但是注意兩點:1)轉義字符的問題;2)不能創建文件夾,文件夾必須預先存在。
1 fn='c://test.txt' 2 fp=open(fn,'w+') 3 fp.write('www.python.com') 4 fp.close() 
View Code

 

三,字典及其基本操作
1,字典定義
     字典:由一對稱之為鍵和值構成,用逗號間隔起來,用花括號括起來就構成了字典。語法結構:
                dict_name={key:value,key:value,key:value,……}
     字典的數據項的值可以是字典,列表等數據類型。
2,基礎操作
1)字典長度:
    len函數可以測得字典的數據項個數。
1 >>> dict1={'a':'b','name':'jeap',12:34}2 >>> len(dict1)3 3
View Code
2)元素值的訪問:
     Python的字典可以通過鍵獲取其所對應的值,而序列型數據字符串,列表則是通過index索引來獲取的。字典的元素的關系比較稀松,是無序的。
1 >>> dict1={'a':'b','name':'jeap',12:34}2 >>> print dict1['a'],dict1[12]3 b 34
View Code

3)元素值的修改:

    通過鍵獲取修改所對應的值。
1  >>> dict1['a']='hello'2 >>> print dict13 {'a': 'hello', 12: 34, 'name': 'jeap'}
View Code

4)元素項的刪除:

     通過del 字典名[鍵]來刪除字典里的元素。
1 >>> del dict1[12]2 >>> print dict13 {'a': 'hello', 'name': 'jeap'}
View Code

5)元素項的增加:

      通過字典名[新鍵]賦值的方式在字典里新增一個數據項。
1 >>> dict1['QQ']='649414754'2 >>> print dict13 {'a': 'hello', 'QQ': '649414754', 'name': 'jeap'}4 >>> dict1['sex']='F'5 >>> print dict16 {'a': 'hello', 'QQ': '649414754', 'name': 'jeap', 'sex': 'F'}
View Code

6)in運算:

     判斷某鍵是否存在于字典里。
1 >>> 'name' in dict12 True3 >>> 'F' in dict14 False
View Code
注意:in運算查找的是Key值,而非value值。
 
四,字典的相關函數
1)clear函數:清空字典數據項。
1 >>> print dict12 {'a': 'hello', 'QQ': '649414754', 'name': 'jeap', 'sex': 'F'}3 >>> dict1.clear()4 >>> print dict15 {}
View Code
2)copy函數:字典復制,與源對象間的關系是備份關系。
1 >>> dict1={'a': 'hello', 'QQ': '649414754', 'name': 'jeap', 'sex': 'F'}2 >>> dict2=dict1.copy()3 >>> print dict24 {'a': 'hello', 'QQ': '649414754', 'name': 'jeap', 'sex': 'F'}
View Code
3)get函數:獲取某鍵鎖對應的值,等價于dict_name[鍵]
1 {'a': 'hello', 'QQ': '649414754', 'name': 'jeap', 'sex': 'F'}2 >>> dict1.get('QQ')3 '649414754'
View Code
4)keys函數:獲取字典所有的key。
1 >>> dict1.keys()2 ['a', 'QQ', 'name', 'sex']
View Code
5)values函數:獲取字典所有的value。
1 >>> dict1.values()2 ['hello', '649414754', 'jeap', 'F']
View Code
6)intems函數:獲取字典所有的key-value。
1 >>> dict1.items()2 [('a', 'hello'), ('QQ', '649414754'), ('name', 'jeap'), ('sex', 'F')]
View Code
7)update函數:更新字典里某鍵(key)的鍵值(value),如果更新的key原字典沒有,則update就向字典里添加一項數據。
1 >>> new={'age':32}  #原字典沒有,新增2 >>> add={'name':'張三'} #原字典存在,更新'jeap'為'張三'3 >>> dict1.update(new)4 >>> dict1.update(add)5 >>> print dict16 {'a': 'hello', 'QQ': '649414754', 'name': '/xd5/xc5/xc8/xfd', 'age': 32, 'sex': 'F'}
View Code
8)dict函數:創建字典。
   下面舉例三種創建字典的方法:
 1 >>> d0=dict() #創建空字典 2 >>> print d0 3 {} 4 >>> d1=dict(name='zhangsan',QQ='123456789',age=23)#通過賦值創建字典 5 >>> print d1 6 {'QQ': '123456789', 'age': 23, 'name': 'zhangsan'} 7 >>> val=['lisi','649414754',25] 8 >>> print val 9 ['lisi', '649414754', 25]10 >>> key=range(1,4)11 >>> d2=dict(zip(key,val))#使用一對列表創建字典12 >>> print d213 {1: 'lisi', 2: '649414754', 3: 25}
View Code
9)pop和popitem函數:pop方法通過鍵key獲取其值value并從字典中刪除該數據項;popitem函數則是隨機移除一個數據項,返回值是元組。
 1 >>> val=['Tom','Jack','Rose','John','Mark'] 2 >>> key=range(1,6) 3 >>> dic=dict(zip(key,val)) 4 >>> print dic 5 {1: 'Tom', 2: 'Jack', 3: 'Rose', 4: 'John', 5: 'Mark'} 6 >>> dic.pop(2) 7 'Jack' 8 >>> dic.popitem() 9 (1, 'Tom')10 >>> print dic11 {3: 'Rose', 4: 'John', 5: 'Mark'}
View Code
10)實踐應用:字典和for循環遍歷字典。
     i)通過in運算和鍵,來訪問字典的值。
 1 >>> key=range(1,6) 2 >>> val=['Tom','Jack','Rose','John','Mark'] 3 >>> dic=dict(zip(key,val)) 4 >>> for x in dic: 5  print dic[x] 6   7   8 Tom 9 Jack10 Rose11 John12 Mark
View Code
     ii)通過items函數返回值為(key,value)元組組成的列表來訪問。
 1 >>> print dic.items() 2 [(1, 'Tom'), (2, 'Jack'), (3, 'Rose'), (4, 'John'), (5, 'Mark')] 3 >>> for (k,v) in dic.items(): 4  print 'dic[',k,']=',v 5   6   7 dic[ 1 ]= Tom 8 dic[ 2 ]= Jack 9 dic[ 3 ]= Rose10 dic[ 4 ]= John11 dic[ 5 ]= Mark12 >>> 
View Code

 五,小結

      本章主要介紹python開發的進階知識,文件的基本操作,字典的相關概念,基本操作運算和相關函數,為以后實戰應用做一個鋪墊,本章存在的遺留問題是,如何調用不在同一目錄文件下的.py自定義模塊?按照書上的代碼未能實現。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 石柱| 天柱县| 长宁县| 常熟市| 萨迦县| 通许县| 泰宁县| 石城县| 冷水江市| 伽师县| 法库县| 汕头市| 连城县| 高阳县| 达日县| 洛宁县| 靖西县| 阜新| 繁昌县| 竹溪县| 仁化县| 黎平县| 咸丰县| 蒙山县| 隆安县| 开远市| 金坛市| 龙泉市| 宝山区| 绥德县| 安宁市| 富锦市| 新晃| 饶阳县| 射阳县| 云林县| 凤城市| 孝义市| 龙山县| 永宁县| 大埔区|