首页 > 代码库 > Python学习系列(五)(文件操作及其字典)

Python学习系列(五)(文件操作及其字典)

Python学习系列(五)(文件操作及其字典)

  Python学习系列(四)(列表及其函数)

一、文件操作
1,读文件
     在以‘r‘读模式打开文件以后可以调用read函数一次性将文件内容全部读出,也可以指定每次read读多少字节,例如:
1 #coding:utf-82 fn=test1.py3 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.txt2  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.txt2 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]=hello2 >>> 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]=6494147542 >>> print dict13 {a: hello, QQ: 649414754, name: jeap}4 >>> dict1[sex]=F5 >>> 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自定义模块?按照书上的代码未能实现。