VII Python(3)基础知识(if、while、for、iterator、generator、文件、pickle)

简介:

表达式和语句:

常用的表达式操作符:

算术运算:+,-,*,/,//截断除法,%,**幂运算

逻辑运算:x or y,x and y,not x

比较运算:<,>,==,<=,>=,!=

一元运算:-x,+x,~x按位取反

三元选择表达式:x if yelse z

成员关系运算:x in y,x not in y

位运算:x | y,x<< y,x >> y,x & y,x ^ y

索引和分片:x[i],x[i:j],x[i:j:stride]

调用:x(...)

取属性:x.ATTRIBUTE

对象实例测试:x is y,x not is y,

匿名函数:lambd aargs: expression

生成器函数发送协议:yield x

元组(),列表[],字典{}

 

运算优先级:

(...)

[...]

{...}

s[i],s[i:j],s[i:j:stride]

s.attribute

s(...)

+x,-y

x**y

*,/,//,%

+,-

<<,>>

&

^异或

|

<,<=,>,>=,==,!=

is,not is

in,not in

not

and

or

lambda

 

语句:

赋值语句(创建引用)

调用语句

print语句(打印对象)

if,elif,else(条件判断)

for,else(序列迭代)

while,else(普通循环)

pass(占位符)

break,continue

def,return

yield

global(命名空间)

from,import(模块属性访问)

class

try,except,finally(捕捉异常)

raise(手动触发异常)

del(删除引用)

assert(调试检查)

with,as(环境管理器)

 

python的比较操作:

所有python对象都支持比较操作,可用于测试相等性、相对大小等;

如果是复合对象,python会检查所有部分,包括自动遍历各级嵌套对象,直到可以得出最终结果;

测试操作符:(==,测试值的相等性;is表达式,测试对象的一致性)

python中不同类型的比较方法(数字,通过相对大小进行比较;字符串,按照字典次序逐字符比较;列表和元组,自左至右比较各部分内容;字典,对排序后的列表(key,value)进行比较);

python中真和假的含义(非0数字为真,否则为假;非空对象为真,否则为假;None则始终为假;任何非0数字和非空对象都为真;数字0、空对象、特殊对象None均为假;比较和相等测试会递归的应用于数据结构中;返回值为TrueFalse

组合条件测试(x and y与运算;x or y或运算;not x非运算)

 

 

条件测试表达式:

语法结构(elif是可选的,若仅用于占位而后再填充相关语句时可使用pass):

if boolean_expression1:

       suite1

elif boolean_expression2:

       suite2

...

else:

       else_suite

三元表达式常用于赋值(max=A if A>B else B):

语法结构(boolean_expressionTrue结果为expression1,否则为expression2):

expression1 if boolean_expression else expression2

A = y if x else z,通常在为某变量设定默认值时使用,等同于:

if x:

       A= y

else:

       A= z

 

 

while循环:

用于编写通用迭代结构,顶端测试为真执行循环体,并会重复多次测试直到为假后执行循环后的其它语句

while语法(else分支可选,只要boolean_expression的结果为True循环执行,boolean_expression的结果为False若有else分支else分支将执行;else代码块,循环正常终止才会执行,如果循环终止是由break导致则else段语句不会执行):

while boolean_expression:

       while_suite

else:

       else_suite

 

 

for循环:

一个通用的序列迭代器,用于遍历任何有序的序列对象内的元素;

可用于字符串、元组、列表和其它的内置可迭代对象,及通过类所创建的新对象;

for语法(通常expression是一个单独的变量或是一个变量序列,一般以元组的形式给出,如果将元组或列表用于expression,则其中的每个数据项都会拆分到表达式的项,如t=[(1,2),(3,4),(5,6)]for (a,b) in t:):

for expression1 initerable:

       for_suite

else:

       else_suite

python也提供了能进行隐性迭代的工具,(有:in成员关系测试;列表解析;mapreducefilter);

python提供了两个内置函数rangezip,用于在for循环中定制特殊的循环;

range是一次性生成所有数据元素都放在内存中,一次性返回连续的整数列表;

xrange一次产生一个数据元素,是用一个生成一个,对于非常大的序列用xrange可节约内存空间;

zip返回并行的元素元组的列表,常用于在for循环中遍历数个序列;

enumerate(产生偏移和元素,range可在非完备遍历中生成索引偏移而非偏移处的元素,如果同时需要偏移索引和偏移元素,使用enumerate()函数,此函数返回一个生成器对象);

for循环比while循环执行速度快,尤其是遍历时要使用for循环;

非完备遍历:

In [52]: s1='how are you these days'

In [53]: for i in range(0,len(s1),2):

  ....:     print s1[i],

  ....:    

h w a e y u t e e d y

修改列表:

In [57]: l1=[1,2,3,4,5]

In [58]: for i in range(len(l1)):

  ....:     l1[i]+=1

  ....:    

In [59]: print l1

[2, 3, 4, 5, 6]

并行遍历zip(取得一个或多个序列为参数,将给定的并排的元素配成元组,返回这些元组的列表,当参数长度不同时,zip会以最短序列的长度为准,可在for循环中用于实现并行迭代,也常用于动态构造字典):

In [60]: l1=[1,2,3,4,5,6,7]

In [61]: l2=['a','b','c','d','e','f','g']

In [62]: zip(l1,l2)

Out[62]: [(1, 'a'), (2, 'b'), (3, 'c'), (4,'d'), (5, 'e'), (6, 'f'), (7, 'g')]

In [63]: d1={}

In [64]: for (k,v) in zip(l1,l2):

  ....:     d1[k]=v

  ....: print d1

  ....:

{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6:'f', 7: 'g'}

产生偏移和元素:

In [66]: s1='hello world'

In [67]: e1=enumerate(s1)

In [68]: e1.next()

Out[68]: (0, 'h')

In [69]: e1.next()

Out[69]: (1, 'e')

In [70]: e1.next()

Out[70]: (2, 'l')

In [71]: e1.next()

Out[71]: (3, 'l')

In [72]: e1.next()

Out[72]: (4, 'o')

 

举例1(逐一显示列表中的所有元素):

方一:

In [2]: l1=[1,2,3,4,5]

In [3]: count=0

In [4]: while count < len(l1):

  ...:     print l1[count]

  ...:     count+=1

  ...:    

1

2

3

4

5

方二:

In [5]: while l1:

  ...:     print l1[0]

  ...:     l1=l1[1:]  #(此句也可写为l1.pop(0)

  ...:    

1

2

3

4

5

方三(逆序显示):

In [11]: l1=[1,2,3,4,5]

In [12]: while l1:

  ....:     print l1[-1]

  ....:     l1.pop()

  ....:    

5

4

3

2

1

方四(推荐使用):

In [16]: for x in l1:

   ....:    print x

   ....:    

1

2

3

4

5

 

举例2(求100以内所有偶数之和):

In [17]: sum=0

In [18]: for i in range(2,100,2):

  ....:     sum+=i

  ....: print sum

  ....:

2450

 

举例三(逐一显示指定字典的所有key,并在最后显示总key数):

方一(推荐使用):

In [19]: d1={'x':1,'y':2,'z':3}

In [20]: keylist=d1.keys()

In [21]: print keylist

['y', 'x', 'z']

In [22]: for i in keylist:

  ....:     print i,

  ....:    

y x z

In [23]: print len(d1)

3

方二:

In [25]: keylist=d1.keys()

In [26]: while keylist:

  ....:     print keylist[0]

  ....:     keylist.pop(0)

  ....: else:

  ....:     print len(d1)

  ....:    

y

x

z

3

 

举例四(创建一个包含了100以内所有奇数的列表):

方一:

In [27]: l1=[]

In [28]: x=1

In [29]: while x<100:

  ....:     l1.append(x)

  ....:     x+=2

  ....: print l1

  ....:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23,25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63,65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

方二(推荐使用):

In [30]: l1=[]

In [31]: for i in range(1,100,2):

  ....:     l1.append(i)

  ....: print l1

  ....:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23,25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63,65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

 

举例五(将两个列表生成字典):

方一:

In [32]: l1=[1,2,3,4,5,6,7]

In [33]:l2=['mon','tue','wed','thu','fri','sat','sun']

In [34]: d1={}

In [35]: count=0

In [36]: if len(l1)==len(l2):

  ....:     while count<len(l1):

  ....:        d1[l1[count]=l2[count]

  ....:         count+=1

  ....: print d1

  ....:        

{1: 'mon', 2: 'tue', 3: 'wed', 4: 'thu', 5:'fri', 6: 'sat', 7: 'sun'}

方二:

In [48]: d1={}

In [49]: if len(l1)==len(l2):

  ....:     for i in range(0,len(l1)):

  ....:         d1[l1[i]]=l2[i]

  ....: print d1

  ....:

{1: 'mon', 2: 'tue', 3: 'wed', 4: 'thu', 5:'fri', 6: 'sat', 7: 'sun'}

 

举例六(逐一分开显示字典中的所有元素):

In [73]: d1={'x':1,'y':2,'z':3}

In [74]: for (k,v) in d1.items():

  ....:     print k,v

  ....:    

y 2

x 1

z 3

 

举例七(逐一显示列表中索引为奇数的元素):

In [76]: l1=['mon','tue','wed','thu','fri','sat','sun']

In [77]: for i in range(1,len(l1),2):

  ....:     print l1[i]

  ....:    

tue

thu

sat

 

举例八(将属于列表1但不属于列表2的所有元素定义为一个新列表3):

In [78]:l1=['mon','tue','wed','thu','fri','sat','sun']

In [79]: l2=['sun','mon']

In [80]: l3=[]

In [81]: for i in l1:

  ....:     if i not in l2:

  ....:         l3.append(i)

  ....: print l3

  ....:

['tue', 'wed', 'thu', 'fri', 'sat']

 

举例九(将列表1中的每个元素从列表2中移除,属于l1不属于l2的忽略):

In [82]: l1=['stu3','stu5']

In [83]: l2=['stu1','stu2','stu3','stu4','stu5']

In [84]: for i in l1:

  ....:     if i in l2:

  ....:         l2.remove(i)

  ....: print l2

  ....:

['stu1', 'stu2', 'stu4']

 

 

减少引用计数:

del VARIABLE_NAME(引用此对象的某变量名称被显示销毁);

给引用此对象的某变量名重新赋值;

list.pop()list.remove()等从容器中移除对象;

容器本身被销毁

 

增加对象的引用计数场景:

变量赋值(对象创建时);

将对象添加进容器时,如list.append()

当对象被当作参数传递给函数时;

为对象创建另外的变量名或多重目标赋值,如s1=s2=s3='ab'

 

python迭代(重复做一件事,iterable可迭代对象,迭代器iterator):

支持每次返回自己所包含的一个成员对象,对象实现了__iter__方法;

可迭代对象(序列类型有strlisttuple;非序列类型有filedict;用户自定义的一些包含了__iner__()__getitem__()方法的类);

dir(list)中有__iter__方法说明此对象支持迭代,某对象内部有__iter____getitem__方法,当这个对象调用此方法时会在内存中创建属于当前迭代器的可迭代对象,使用此内存地址的对象就可实现迭代,如i1=l1.__iter__()i1=iter(l1),再用 i1.next()遍历每个元素,遍历完成后迭代器不会从头开始再迭代;

l1.__iter__(),返回迭代器地址,要引用此地址如i1=l1.__iter__()

iterator又称cursor游标,它是程序设计中的软件设计模式,是一种可在容器container上实现元素遍历的接口,iterator是一种特殊的数据结构,在python中以对象形式存在,对于一个集体中的每个元素,想要执行遍历,针对这个集体的迭代器定义了遍历集体中每个元素的顺序或方法,help(iter)

python中,iterator是遵循迭代协议的对象,使用iter()可从任何序列对象中得到迭代器,若要实现迭代器,需要在类中定义next()方法(python3.*中是__next__()),要使迭代器指向下一个元素,使用函数next(),当没有元素时引发StopIteration异常;

for循环可用于任何可迭代对象,for循环开始时,会通过迭代协议传递给iter()内置函数,从而能够从可迭代对象中获得一个迭代器,返回的对象含有需要的next()方法;

python列表解析是迭代机制的一种应用,常用于实现创建新的列表,因此要放在[]中,语法:

[expression for iter_var in iterable]

[expression for iter_var in iterable ifcond_expr]

举例1(这种方式性能较差):

In [91]: l1=[1,2,3,4,5,6,7,8,9]

In [92]: l2=[]

In [93]: for i in l1:

  ....:     l2.append(i**2)

  ....: print l2

  ....:

[1, 4, 9, 16, 25, 36, 49, 64, 81]

举例2(推荐使用):

In [88]: l1=[x**2 for x in range(1,10)]

In [89]: print l1

[1, 4, 9, 16, 25, 36, 49, 64, 81]

举例3

In [94]: import os

In [95]: files=os.listdir('/var/log')

In [96]: l1=[filename for filename in filesif filename.endswith('.log')]

In [97]: print l1

['anaconda.program.log','spice-vdagent.log', 'anaconda.yum.log', 'yum.log', 'vmware-tools-upgrader.log','boot.log', 'anaconda.ifcfg.log', 'pm-powersave.log', 'anaconda.storage.log','anaconda.log', 'Xorg.0.log', 'dracut.log', 'wpa_supplicant.log']

举例4

In [101]: for i in [j**2 for j inrange(1,10) if j%2==0]:

  .....:     print i/2,

   .....:    

2 8 18 32

举例5

In [102]: l1=['x','y','z']

In [103]: l2=[1,2,3]

In [104]: l3=[(i,j) for i in l1 for j inl2]

In [105]: l4=[(i,j) for i in l1 for j in l2if j!=1]

In [106]: print l3

[('x', 1), ('x', 2), ('x', 3), ('y', 1),('y', 2), ('y', 3), ('z', 1), ('z', 2), ('z', 3)]

In [107]: print l4

[('x', 2), ('x', 3), ('y', 2), ('y', 3),('z', 2), ('z', 3)]

注:若原列表元素本身就很多,列表解析后的结果又呈几何倍数增长,这会占用大量内存,这时要用到扩展列表解析也叫生成器generator[]换为()),类似rangexrange的区别

 

generator生成器:

python2.4引入,并不真正创建数字列表,而是返回一个生成器对象,此对象在每次计算出一个条目后,把这个条目产生yield出来,生成器表达式使用了惰性计算或称作延迟求值的机制;

enumerate()函数返回一个生成器对象(range可在非完备遍历中用于生成索引偏移,而非偏移的元素,如果同时要偏移索引和偏移元素,可使用此函数);

序列过长,且每次只需要获取一个元素时,应考虑使用生成器表达式而不是列表解析;

语法:

(expression for iter_var in iterable)

(expression for iter_var in iterable ifcond_expr)

举例1

In [108]: g1=(i**2 for i in range(1,5))  #(要通过变量引用,若不引用是其内存地址,调用一次生成一个值)

In [109]: g1.next()

Out[109]: 1

In [110]: g1.next()

Out[110]: 4

In [111]: g1.next()

Out[111]: 9

In [112]: g1.next()

Out[112]: 16

举例2

In [119]: for j in (i**2 for i inrange(1,11) if i%2==0):

  .....:     print j/2

  .....:    

2

8

18

32

50

举例3

In [124]: url='www.magedu.com'

In [125]: g1=enumerate(url)

In [126]: g1.next()

Out[126]: (0, 'w')

In [127]: g1.next()

Out[127]: (1, 'w')

In [128]: g1.next()

Out[128]: (2, 'w')

In [129]: g1.next()

Out[129]: (3, '.')

In [130]: g1.next()

Out[130]: (4, 'm')

 

python文件对象:

FSOS用于明确磁盘或分区上的文件的方法和数据结构(即在磁盘上组织文件的方法);

计算机文件(或称文件、电脑档案、档案)是存储在某种长期储存设备或临时存储设备中的一段数据流,且归属于计算机FS管理之下;

文件是计算机中由OS管理的具有名字的存储区域,在linuxOS上文件被看成是字节序列;

open(),此内置函数用于打开文件和创建文件对象,语法:

open(filename[,mode[,bufsize]])

open()方法接收三个参数,文件名、模式和缓冲区参数:

open()函数返回的是一个文件对象(内存中的位置,要用变量引用);

mode指定文件的打开模式,rwa附加、r+w+a+rbwb(后面有加号表示同时支持输入输出操作即读入写出,后面有b表示以二进制方式打开);

bufsize定义输入输出缓存(0表示禁用,无输出缓存;1表示使用缓存,要指定缓冲区大小;负数表示使用系统默认设置;正数表示使用近似指定大小的缓冲);

In [1]: f1=open('/etc/passwd','r')

In [2]: type(f1)

Out[2]: file

In [3]: f1.<TAB>

f1.close       f1.errors      f1.isatty      f1.newlines    f1.readinto    f1.seek        f1.truncate    f1.xreadlines

f1.closed      f1.fileno      f1.mode        f1.next        f1.readline    f1.softspace   f1.write      

f1.encoding    f1.flush       f1.name        f1.read        f1.readlines   f1.tell        f1.writelines 

In [3]: f1.next()

Out[3]: 'root:x:0:0:root:/root:/bin/bash\n'

In [4]: f1.next()

Out[4]:'bin:x:1:1:bin:/bin:/sbin/nologin\n'

In [5]: f1.next()

Out[5]:'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n'

In [6]: print dir(file)

['__class__', '__delattr__', '__doc__','__enter__', '__exit__', '__format__', '__getattribute__', '__hash__','__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__','__setattr__', '__sizeof__', '__str__', '__subclasshook__','close', 'closed', 'encoding', 'errors', 'fileno', 'flush','isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline','readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines','xreadlines']

In [7]: help(f1.fileno)  #(文件描述符,012系统默认的标准输入、标准输出、标准错误输出)

fileno() -> integer "filedescriptor".

This is needed for lower-level fileinterfaces, such os.read().

In [8]: f1.fileno()

Out[8]: 7

In [56]: f1.readline()  #(一次读取一行并返回指针,若使用f1.next()则不会移动指针)

Out[56]:'root:x:0:0:root:/root:/bin/bash\n'

In [57]: f1.readline()

Out[57]:'bin:x:1:1:bin:/bin:/sbin/nologin\n'

In [58]: f1.tell()   #(返回当前指针在文件中的位置,单位是字节,若是追加会将指针移至最后)

Out[58]: 65

In [59]: f1.readlines()   #(将文件所有内容按行生成列表,行结束符也在列表元素中,若文件很大时会占用内存空间)

Out[59]:

['daemon:x:2:2:daemon:/sbin:/sbin/nologin\n',

 'adm:x:3:4:adm:/var/adm:/sbin/nologin\n',

 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n',

……

'nagios:x:501:502::/home/nagios:/bin/bash\n']

In [60]: help(file.seek)

seek(offset[, whence])-> None.  Move to new file position.whence值有012表示起点位置,默认0表示从文件头,1表示从当前位置,2表示从文件尾部;offset表示偏移量)

In [61]: f1.seek(0)  #f1.seek(0,2),从文件尾部偏移0byte

In [62]: f1.tell()

Out[62]: 0

In [63]: f1.seek(65)

In [64]: f1.readline()

Out[64]:'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n'

In [65]: f1.tell()

Out[65]: 105

In [66]: help(file.read)

read([size]) -> readat most size bytes, returned as a string.(以bytes为单位读字串)

In [67]: f1.read(10)

Out[67]: 'adm:x:3:4:'

In [68]: f1.tell()

Out[68]: 115

In [69]: f1.next()

Out[69]: 'adm:/var/adm:/sbin/nologin\n'

In [70]: f1.tell()

Out[70]: 1515

In [73]: help(file.name)

Help on member descriptor__builtin__.file.name:(获取当前文件名,name是属性不是方法)

In [74]: f1.name

Out[74]: '/etc/passwd'

In [75]: s1='abc'

In [76]: s2='xyz'

In [77]: s1.join(s2)   #(以s1为分隔符连接s2中的每个元素)

Out[77]: 'xabcyabcz'

In [78]: ' '.join(s1)   #(通常这么用,' '.join,在join前面是分隔符delimeter此例是空格)

Out[78]: 'a b c'

In [79]: ' '.join(s2)

Out[79]: 'x y z'

In [80]: s1+s2   #(连接两个字串)

Out[80]: 'abcxyz'

In [81]:help(file.writelines)

writelines(sequence_of_strings)-> None.  Write the strings to thefile.(将列表中的所有元素的字符串连接)

In [85]: f1=open('/tmp/test.txt','r+')

In [86]: f1.writelines(l1)   #(此种方式最终test.txt中保存的内容杂乱无章)

In [87]: f1.flush()

In [88]: l2=[i+'\n' for i inos.listdir('/etc')]   #(此种方式会将每个文件或目录换行显示)

In [89]: f1.writelines(l2)

In [90]: f1.flush()

[root@localhost ~]# cat /tmp/test.txt

rc.sysinit

favicon.png

ld.so.cache

libreport

……

In [91]:help(file.isatty)

isatty() -> true orfalse.  True if the file is connected toa tty device.(判断某一文件是否是终端设备文件)

In [96]: f1=open('/dev/tty')

In [97]: f1.isatty()

Out[97]: True

In [99]:help(file.truncate)

truncate([size]) ->None.  Truncate the file to at most sizebytes.(文件截取)

In [113]: f1.truncate(f1.tell())   #(指针所在处之后的内容全部删掉)

In [115]: f1.closed   #closed是属性,判断文件是否为关闭状态)

Out[115]: False

In [116]: f1.encoding   #(获取当前文件编码)

In [117]: f1.mode   #(获取当前文件打开时的模式)

Out[117]: 'a+'

In [118]: f1.newlines   #(显示指针所在位置之前的行结束符)

In [121]: f1.close()

In [122]: f1.closed

Out[122]: True

 

 

In [1]: import os

In [2]: os.<TAB>   #os模块下有很多方法和属性,将OS中用C语言编写的命令用python封装即可调用)

Display all 207 possibilities? (y or n)

os.EX_CANTCREAT      os.SEEK_END          os.execve            os.lstat             os.setuid

os.EX_CONFIG         os.SEEK_SET          os.execvp            os.major             os.spawnl

os.EX_DATAERR        os.TMP_MAX           os.execvpe           os.makedev           os.spawnle

os.EX_IOERR          os.UserDict          os.extsep            os.makedirs          os.spawnlp

os.EX_NOHOST         os.WCONTINUED        os.fchdir            os.minor             os.spawnlpe

os.EX_NOINPUT        os.WCOREDUMP         os.fchmod            os.mkdir             os.spawnv

os.EX_NOPERM         os.WEXITSTATUS       os.fchown            os.mkfifo            os.spawnve

os.EX_NOUSER         os.WIFCONTINUED      os.fdatasync         os.mknod             os.spawnvp

os.EX_OK             os.WIFEXITED         os.fdopen            os.name              os.spawnvpe

os.EX_OSERR          os.WIFSIGNALED       os.fork              os.nice              os.stat

os.EX_OSFILE         os.WIFSTOPPED        os.forkpty           os.open              os.stat_float_times

os.EX_PROTOCOL       os.WNOHANG           os.fpathconf         os.openpty           os.stat_result

os.EX_SOFTWARE       os.WSTOPSIG          os.fstat             os.pardir            os.statvfs

os.EX_TEMPFAIL       os.WTERMSIG          os.fstatvfs          os.path              os.statvfs_result

os.EX_UNAVAILABLE    os.WUNTRACED         os.fsync             os.pathconf          os.strerror

os.EX_USAGE          os.W_OK              os.ftruncate         os.pathconf_names    os.symlink

os.F_OK              os.X_OK              os.getcwd            os.pathsep           os.sys

os.NGROUPS_MAX       os.abort             os.getcwdu           os.pipe              os.sysconf

os.O_APPEND          os.access            os.getegid           os.popen             os.sysconf_names

os.O_ASYNC           os.altsep            os.getenv            os.popen2            os.system

os.O_CREAT           os.chdir             os.geteuid           os.popen3            os.tcgetpgrp

os.O_DIRECT          os.chmod             os.getgid            os.popen4            os.tcsetpgrp

os.O_DIRECTORY       os.chown             os.getgroups         os.putenv            os.tempnam

os.O_DSYNC           os.chroot            os.getloadavg        os.read              os.times

os.O_EXCL            os.close             os.getlogin          os.readlink          os.tmpfile

os.O_LARGEFILE       os.closerange        os.getpgid           os.remove            os.tmpnam

os.O_NDELAY          os.confstr           os.getpgrp           os.removedirs        os.ttyname

os.O_NOATIME         os.confstr_names     os.getpid            os.rename            os.umask

os.O_NOCTTY          os.ctermid           os.getppid           os.renames           os.uname

os.O_NOFOLLOW        os.curdir            os.getresgid         os.rmdir             os.unlink os.O_NONBLOCK        os.defpath           os.getresuid         os.sep               os.unsetenv

os.O_RDONLY          os.devnull           os.getsid            os.setegid           os.urandom

os.O_RDWR            os.dup               os.getuid            os.seteuid           os.utime

os.O_RSYNC           os.dup2              os.initgroups        os.setgid            os.wait

os.O_SYNC            os.environ           os.isatty            os.setgroups         os.wait3

os.O_TRUNC           os.errno             os.kill              os.setpgid           os.wait4

os.O_WRONLY          os.error             os.killpg            os.setpgrp           os.waitpid

os.P_NOWAIT          os.execl             os.lchown            os.setregid          os.walk

os.P_NOWAITO         os.execle            os.linesep           os.setresgid         os.write

os.P_WAIT            os.execlp            os.link              os.setresuid        

os.R_OK              os.execlpe           os.listdir           os.setreuid         

os.SEEK_CUR          os.execv             os.lseek             os.setsid

 

与目录相关:

os.chdir(path)(改变当前工作目录)

os.fchdir(fildes)(改变当前的工作目录到由文件描述符fd表示的目录,描述符必须是指向一个打开的目录而不是一个打开的文件)

os.chroot(path)(设定当前进程的根目录)

os.listdir(path)(显示指定目录下的所有文件名)

os.mkdir(path[,mode=0777])(创建指定目录)

os.makedirs(path[,mode=0777])(递归创建指定目录,类似系统中mkdir -p /path/to/

os.getcwd()(获取当前目录路径)

os.rmdir(path)(删除目录)

os.removedirs(path)(删除多级目录,类似rm -rf

os.stat(path)

与文件相关:

os.remove(path)(删除文件,同os.unlink(path)

os.unlink(path)(删除链接文件,Remove a file (same asremove(path))

os.rename(old.new)(重命名文件或目录Rename a file or directory.)

os.stat(path)(返回文件状态信息Perform a stat system call on the given path.

os.symlink(src,dst)(创建链接文件)

os.utime(path,None)(更新文件时间戳为当前时间,访问时间和修改时间,set theaccess and modified times to the current time

os.utime(path,(atime,mtime))       (更新文件时间为指定时间,Set the access and modified time of the file to the given values

os.tmpfile()(创建一临时文件,Create a temporary file with no directory entries.

os.mkfifo(filename[,mode=0666])(创建命名管道)

os.mknod(filename[,mode=0600,device])Create a filesystem node (file,device special file or named pipe)named filename.创建设备文件)

os.makedev(major,minor)(根据指定的主设备号、次设备号创建设备,Composes a rawdevice number from the major and minor device numbers.

os.major(device)(根据指定的设备获取主设备号,Extracts a devicemajor number from a raw device number.

os.minor(device)(根据指定的设备获取次设备号,Extracts a deviceminor number from a raw device number.

os.walk(top,topdown=True,onerror=None,followlinks=False)(将多级目录生成元组,子目录及其下的文件分别是列表中的元素,Foreach directory in the directory tree rooted at top (including top itself, butexcluding '.' and '..'), yields a 3-tuple

举例:

In [2]: import os

In [3]: g1=os.walk('/tmp')

In [4]: g1.next()

Out[4]:

('/tmp',

 ['VMwareDnD', '.ICE-unix','pulse-MUK7gfWor9cA', '.esd-500'],

 ['test.txt'])

In [5]: g1.next()

Out[5]: ('/tmp/VMwareDnD', [], [])

In [6]: g1.next()

Out[6]: ('/tmp/.ICE-unix', [], [])

In [7]: g1.next()

Out[7]: ('/tmp/pulse-MUK7gfWor9cA', [],['native'])

举例(遍历目录,连接目录与文件,常用):

In [19]: g=os.walk('/tmp/test')

In [20]: for path,d,filelist in g:

   for filename in filelist:

       print os.path.join(path,filename)

  ....:        

/tmp/test/test3/t2.txt

/tmp/test/test2/test21/t1.txt

与访问权限相关:

os.access(path,mode)(检查某用户对指定文件是否有访问权限,此处mode为用户的uidgidUse the real uid/gid to test for access to a path.

os.chmod(path,mode)(修改权限,mode0755Change the access permissions of a file.

os.chown(path,uid,gid)(修改指定文件的属主属组,Change the owner andgroup id of path to the numeric uid and gid.

os.umask(new_mask)(修改默认权限模式,Set the current numericumask and return the previous umask.

与文件描述符相关:

os.open(filename,flag[,mode=0777])Open a file (for low level IO).

os.read(fd,buffersize)Read a file descriptor.

os.write(fd,string)Write a string to a filedescriptor.

与文件路径相关:

In [5]: os.path.<TAB>

os.path.abspath                     os.path.getmtime                    os.path.relpath

os.path.altsep                      os.path.getsize                     os.path.samefile

os.path.basename                    os.path.isabs                       os.path.sameopenfile

os.path.commonprefix                os.path.isdir                       os.path.samestat

os.path.curdir                      os.path.isfile                      os.path.sep

os.path.defpath                     os.path.islink                      os.path.split

os.path.devnull                     os.path.ismount                     os.path.splitdrive

os.path.dirname                     os.path.join                        os.path.splitext

os.path.exists                      os.path.lexists                     os.path.stat

os.path.expanduser                  os.path.normcase                   os.path.supports_unicode_filenames

os.path.expandvars                  os.path.normpath                    os.path.sys

os.path.extsep                      os.path.os                          os.path.walk

os.path.genericpath                 os.path.pardir                      os.path.warnings

os.path.getatime                    os.path.pathsep                    

os.path.getctime                    os.path.realpath

os.path.basename(path)(路径基名,Returns the final component ofa pathname

os.path.dirname(path)(路径目录名,Returns the directorycomponent of a pathname

os.path.join(a,*p)Join two or more pathnamecomponents, inserting '/' as needed.

os.path.split(p)(返回dirname()basename()结果的元组,Split a pathname.  Returns tuple "(head, tail)" where"tail" is everything after the final slash.  Either part may be empty.

os.path.splitext(p)(返回filename文件名、文件扩展名extention(扩展名包括dot点)为元组,Split the extension from apathname.

os.path.getatime(filename)Return the last access time of afile, reported by os.stat()

os.path.getctime(filename)Return the metadata change time ofa file, reported by os.stat().

os.path.getmtime(filename)Return the last modification timeof a file, reported by os.stat().

os.path.getsize(filename)Return the size of a file, reportedby os.stat().

os.path.exists(path)(判断指定文件是否存在,Test whether a pathexists.  Returns False for brokensymbolic links

os.path.isabs(s)(判断指定路径是否绝对路径,Test whether a path isabsolute

os.path.isdir(s)(判断路径是否存在且为目录,Return true if thepathname refers to an existing directory.

os.path.isfile(path)(判断文件是否存在且为普通文件,Test whether a pathis a regular file

os.path.islink(path)(判断文件是否存在且为链接文件,Test whether a pathis a symbolic link

os.path.ismount(path)(判断文件是否存在且为挂载点,Test whether a pathis a mount point

os.path.samefile(f1,f2)(判断两个路径是否指向同一个文件,Test whether twopathnames reference the same actual file

举例:

In [20]:dir1=os.path.dirname('/etc/sysconfig/network-scripts/ifcfg-eth0')

In [21]: print dir1

/etc/sysconfig/network-scripts

In [22]:file1=os.path.basename('/etc/sysconfig/network-scripts/ifcfg-eth0')

In [23]: print file1

ifcfg-eth0

[root@localhost ~]# mkdir /tmp/testdir

[root@localhost ~]# touch /root/test.txt

In [1]: import os

In [2]:dir1=os.path.dirname('/tmp/testdir')

In [3]:file1=os.path.basename('/root/test.txt')

In [4]: os.path.join(dir1,file1)

Out[4]: '/tmp/test.txt'

In [9]: for file in os.listdir('/tmp'):

   print os.path.join('/tmp',file)

  ...:    

/tmp/VMwareDnD

/tmp/testdir

/tmp/.ICE-unix

/tmp/pulse-MUK7gfWor9cA

/tmp/test.txt

/tmp/.esd-500

In [12]:os.path.split('/etc/sysconfig/network-scripts/ifcfg-eth0')

Out[12]: ('/etc/sysconfig/network-scripts','ifcfg-eth0')

In [13]:os.path.splitext('/etc/sysconfig/network-scripts/ifcfg-eth0')

Out[13]: ('/etc/sysconfig/network-scripts/ifcfg-eth0','')

In [15]: os.path.splitext('/root/test.txt')

Out[15]: ('/root/test', '.txt')

举例(判断文件是否存在,存在则打开,可让用户通过键盘反复输入多行数据追加至文件中):

[root@localhost ~]# vim test.py

-------------------script start-------------------

#!/usr/bin/python2.7

#filename:test.py

import os

filename='/tmp/test.txt'

if os.path.isfile(filename):

       f1=open(filename,'a+')

while True:

       line=raw_input('Enter something:')

       if line=='q' or line=='quit':

                break

       f1.write(line+'\n')

f1.flush()

f1.close()

--------------------script end---------------------

[root@localhost ~]# chmod 755 test.py

[root@localhost ~]# ./test.py

Enter something:i am jowin

Enter something:who are you

Enter something:hehe

Enter something:q

[root@localhost ~]# cat /tmp/test.txt

i am jowin

who are you

hehe

 

 

picklemarshal对象持久存储(保存了对象的原数据结构,流式化存在文件中):

DBM(仅写数据库,未实现流式化);shelve模块(既写入DB,又实现流式化);

In [1]: d1={'x':1,'y':2,'z':3}

In [2]: f1=open('/tmp/test.txt','w+')

In [3]: f1.write(d1)   #(直接将对象写入文件会报错,要通过picklemarshal实现)

---------------------------------------------------------------------------

TypeError                                 Traceback(most recent call last)

<ipython-input-3-03e18951d68d> in<module>()

----> 1 f1.write(d1)

TypeError: expected acharacter buffer object

 

In [4]: import pickle

In [5]: pickle.<TAB>

Display all 116 possibilities? (y or n)

pickle.APPEND                pickle.EXT4                  pickle.ModuleType            pickle.TUPLE

pickle.APPENDS               pickle.EllipsisType          pickle.NEWFALSE              pickle.TUPLE1

pickle.BINFLOAT              pickle.FALSE                 pickle.NEWOBJ                pickle.TUPLE2  ……

 

用法:

pickle.dump(obj,file,protocol=None)(将对象写入文件)

pickle.load(file)(将对象从文件中恢复,要使用变量引用否则得到的是内存地址)

 

In [6]: pickle.dump(d1,f1)

In [7]: f1.flush()

In [8]: f1.close()

[root@localhost ~]# cat /tmp/test.txt

(dp0

S'y'

p1

I2

sS'x'

p2

I1

sS'z'

p3

I3

s.

In [12]: f2=open('/tmp/test.txt')

In [13]: d2=pickle.load(f2)

In [14]: print d2

{'y': 2, 'x': 1, 'z': 3}

 


copy模块,python对内存的使用(浅拷贝与深拷贝):

copy.copy()浅拷贝(对引用的拷贝,只拷贝父对象(变量引用));

copy.deepcopy()深拷贝(对对象资源的拷贝);

 

In [1]: import copy

In [3]: copy.<TAB>

copy.Error           copy.copy            copy.dispatch_table  copy.name            copy.weakref        

copy.PyStringMap     copy.deepcopy        copy.error           copy.t

In [3]: help(copy.copy)

copy(x)

   Shallow copy operation on arbitrary Python objects.

deepcopy(x, memo=None,_nil=[])

   Deep copy operation on arbitrary Python objects.

wKioL1dqSKuxVquxAAAhwhjKsXg264.jpg

In [5]: a=[1,2,3]

In [6]: b=a

In [7]: id(a)

Out[7]: 20685600

In [8]: id(b)

Out[8]: 20685600

In [9]: a.append(4)

In [10]: a

Out[10]: [1, 2, 3, 4]

In [11]: b

Out[11]: [1, 2, 3, 4]

In [12]: id(a)

Out[12]: 20685600

In [13]: id(b)

Out[13]: 20685600

 

In [14]: a=[1,2,3,['a','b','c']]

In [15]: b=a

In [16]: c=copy.copy(a)

In [17]: id(a)

Out[17]: 20688120

In [18]: id(b)

Out[18]: 20688120

In [19]: id(c)

Out[19]: 20673096

In [20]: a.append('f')

In [21]: a

Out[21]: [1, 2, 3, ['a', 'b', 'c'], 'f']

In [22]: b

Out[22]: [1, 2, 3, ['a', 'b', 'c'], 'f']

In [23]: c

Out[23]: [1, 2, 3, ['a', 'b', 'c']]

In [24]: id(a[0])

Out[24]: 8543336

In [25]: id(c[0])

Out[25]: 8543336

In [26]: id(a[3])

Out[26]: 20688840

In [27]: id(c[3])

Out[27]: 20688840

 




本文转自 chaijowin 51CTO博客,原文链接:http://blog.51cto.com/jowin/1788548,如需转载请自行联系原作者
相关文章
|
16天前
|
Python
【python】python跨文件使用全局变量
【python】python跨文件使用全局变量
|
25天前
|
监控 数据处理 索引
使用Python批量实现文件夹下所有Excel文件的第二张表合并
使用Python和pandas批量合并文件夹中所有Excel文件的第二张表,通过os库遍历文件,pandas的read_excel读取表,concat函数合并数据。主要步骤包括:1) 遍历获取Excel文件,2) 读取第二张表,3) 合并所有表格,最后将结果保存为新的Excel文件。注意文件路径、表格结构一致性及异常处理。可扩展为动态指定合并表、优化性能、日志记录等功能。适合数据处理初学者提升自动化处理技能。
21 1
|
30天前
|
存储 并行计算 Java
Python读取.nc文件的方法与技术详解
本文介绍了Python中读取.nc(NetCDF)文件的两种方法:使用netCDF4和xarray库。netCDF4库通过`Dataset`函数打开文件,`variables`属性获取变量,再通过字典键读取数据。xarray库利用`open_dataset`打开文件,直接通过变量名访问数据。文中还涉及性能优化,如分块读取、使用Dask进行并行计算以及仅加载所需变量。注意文件路径、变量命名和数据类型,读取后记得关闭文件(netCDF4需显式关闭)。随着科学数据的增长,掌握高效处理.nc文件的技能至关重要。
107 0
|
1月前
|
Python
python用户输入和while循环(四)
python用户输入和while循环(四)
26 1
|
1月前
|
安全 Python
python用户输入和while循环(二)
python用户输入和while循环(二)
17 0
|
1月前
|
Python
python中if语句(二)
python中if语句(二)
19 0
|
1月前
|
Python
python用户输入和while循环(一)
python用户输入和while循环(一)
16 0
|
1月前
|
存储 索引 Python
python用户输入和while循环(五)
python用户输入和while循环(五)
17 0
|
1月前
|
Python
python用户输入和while循环(三)
python用户输入和while循环(三)
19 0
|
1月前
|
存储 算法 索引
python用户输入和while循环(六)
python用户输入和while循环(六)
18 0

热门文章

最新文章