文件系统和文件
创建一个文件
readline()与readlines()区别
查看指针指向位置
w+写入模式
访问权限
文件的权限修改
修改文件的属主 属组
import pickle 将内存持久存入文件中
函数
匿名函数 lambda
filter过滤器
映射器
函数闭包
生成器遍历
生成器泰列表
yield与生成器
生成器自身是可以迭代 的
装饰器
带有参数的装饰器
python类与面向对象
我的第一个python类
方法构造器__init__
python父类的继承
谁是谁的子类 判断!
自定义模块路径
制作模块包
python 异常
文件系统和文件
In [20]: f1=open("/etc/passwd" ,"r") 打开一个文件
In [21]: f1.next()
Out[21]:'root:x:0:0:root:/root:/bin/bash\n'
In [22]: f1.next()
Out[22]: 'bin:x:1:1:bin:/bin:/sbin/nologin\n'
In [23]: f1.close() 关闭
In [24]: f1.next() 会报错
readline()与readlines()区别
In [25]:f1=open("/etc/passwd" ,"r")
In [26]: f1.readline()
Out[26]:'root:x:0:0:root:/root:/bin/bash\n'
In [27]: f1.readlines() 以列表的形式返回元素
Out[27]:
['bin:x:1:1:bin:/bin:/sbin/nologin\n',
'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n',
'adm:x:3:4:adm:/var/adm:/sbin/nologin\n',
………………………………
In [64]: f1.seek(0) 恢复指针到0
In [65]: f1.tell() 查看指针指向位置,然后指向下一个
Out[65]: 0
In [66]: f1.read(10)
Out[66]: 'root:x:0:0'
In [67]: f1.read(20)
Out[67]:':root:/root:/bin/bash\nbin:x:1:1
In [70]: f1.tell()
Out[70]: 210查看指针指向位置,然后指向下一个
In [71]: f1.next()
Out[71]: 'sync\n'
In [72]: f1.next()
Out[72]:'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n'
In [76]: f1.name
Out[76]: '/etc/passwd'
修改文件
f1=open('/etc/passwd',"r+") r+ 读写模式
w+写入模式必须要有换行符\n 否则会清空文件内容
In [8]: f1.tell()查看指针指向位置
Out[8]: 0
In [14]: f1.seek(0,2)
In [15]: f1.tell()查看指针指向位置
Out[15]: 1887
f1.write("a new line\n") 写入命令
In [1]: import os
In [2]: l2 = os.listdir("/etc")
In [3]: print l2
['bashrc', 'chkconfig.d','xdg', 'pm', ……………………
In [4]: l3=[i for i in os.listdir("/etc")]
In [5]: print l3
['bashrc', 'chkconfig.d','xdg………………………………
In [6]: l3=[i+'haha\n' for i in os.listdir("/etc")]
In [7]: print l3
['bashrchaha\n', 'chkconfig.dhaha\n', 'xdghaha\n', '
创建一个文件,把l3写进去
In [8]:f4=open('/tmp/test','w+')
In [9]: f4.writelines(l3)
In [10]: f4.flush() 把内存的内容同步到磁盘 OK
[root@localhost ~]# cat/tmp/test
bashrchaha
chkconfig.dhaha
xdghaha
pmhaha
DIR_COLORS.256colorh
In [17]: f4.seek(0)
In [18]: f4.readlines()
Out[18]:
['bashrchaha\n',
'chkconfig.dhaha\n',
'xdghaha\n',
'pmhaha\n',
.truncate截取到此,之后的文件内容都不要
In [19]: f4.seek(0)
In [20]: f4.readline()
Out[20]: 'bashrchaha\n'
In [21]: f4.readline()
Out[21]: 'chkconfig.dhaha\n'
In [22]: f4.readline()
Out[22]: 'xdghaha\n'
In [23]: f4.readline()
Out[23]: 'pmhaha\n'
In [24]:f4.truncate(f4.tell())
In [25]: f4.seek(0)
你看看
In [26]: f4.readlines()
Out[26]: ['bashrchaha\n','chkconfig.dhaha\n', 'xdghaha\n', 'pmhaha\n']
In[28]: f4.mode 获取当前文件的打开模式
Out[28]:'w+'
In[30]: f4.closed 查看文件是否关闭
Out[30]:True
创建目录的接口
In [31]:os.mkdir("/tmp/haha")
获取当前操作的路径
In [33]: os.getcwd()
Out[33]: '/root'
更改操作路径
In [34]:os.chdir("/tmp")
In [35]: os.getcwd()
Out[35]: '/tmp'
获取文件 1的状态
In [36]:os.stat("/tmp/haha/1")
Out[36]:posix.stat_result(st_mode=33188, st_ino=1441801, st_dev=64768L, st_nlink=1,st_uid=0, st_gid=0, st_size=0, st_atime=1431609591, st_mtime=1431609591,st_ctime=1431609591)
递归生成目录
In [37]:os.makedirs("/e/r/t")
创建快捷方式
In [38]: os.getcwd()
Out[38]: '/tmp'
In [39]:os.symlink("jj","kk")
你看看
-rw-r--r-- 1 root root 0 May 14 21:34 jj
lrwxrwxrwx 1 root root 2 May 14 21:35 kk -> jj
g1=os.walk("/etc")
In [41]: g1.next() 遍历出来
Out[41]:
('/etc', 顶级目录
['chkconfig.d',
'xdg',
'pm',
'vsftpd',
访问权限
In [44]:os.access("jj",0) 0就是root
Out[44]: True
In [45]:os.access("jj",20)
Out[45]: False
文件的权限修改
In [47]:os.chmod("jj",0677)
你看看
-rw-r----- 1 root root 0 May 14 21:34 jj
-rw-rwxrwx 1 root root 0 May 14 21:34 jj
修改文件的属主 属组
[root@localhost tmp]# useraddhaha
[root@localhost tmp]# id haha
uid=503(haha) gid=503(haha)groups=503(haha)
os.chown("jj",503,503)
-rw-rwxrwx 1 root root 0 May 14 21:34 jj
-rw-rwxrwx 1 haha haha 0 May 14 21:34 jj
import os.path
dir1 =os.path.dirname("/etc/sysconfig/network-scripts/")
In [53]: print dir1
/etc/sysconfig/network-scripts
#!/usr/local/python27/bin/python2.7
#
import os
import os.path
filename='/home/a.txt'
if os.path.isfile(filename):
f1=open(filename,'a+')
while True:
line = raw_input("enter ")
if line =='q' or line =='quit' :
break
f1.write(line+'\n')
f1.close()
import pickle 将内存持久存入文件中
函数
返回这个函数
函数变量,本地没有去全局(global)找
In [1]: def f1():
...: x=6
...: def f2():
...: y="welcome"
...: print x,y
...: return f2
...:
In [2]: a1=f1()
In [4]: type (a1)
Out[4]: function
In [9]: a1()
6 welcome 6 闭包的记忆效应
函数举例
In [10]: def f2(x,y):
....: print x+y
In [11]: f2(4,8)
12
In [13]:f2("LCL"," linux")
LCL linux
默认是元组
默认是字典
混合
分解赋值
元素个数不匹配会出错
自动匹配
匿名函数 lambda
In [14]: lambda x,y:x+y
Out[14]: <function__main__.<lambda>>
In [15]: f2=lambda x,y:x+y
In [16]: f2(3,9)
Out[16]: 12
引用
In [17]: l3 = [(lambdax:x*3),(lambda y:y*5)]
In [18]: for i in l3 :
....: print i(3)
....:
9
15
函数式编程
filter过滤器
In [19]:l1=[4,8,6,4,5,6,7,8,9,23,9]
In [20]: def fun1(x):
....: if x > 4:
....: return True
....: else:
....: return False
In [22]: filter(fun1 ,l1)
Out[22]: [8, 6, 5, 6, 7, 8,9, 23, 9]
map
这个功能略吊
In [25]: l1=[ 2, 3, 4, 5, 6,7, 8, 9, 10, 11]
In [26]: l2=[4, 5, 6, 7, 8,9, 10, 11, 12, 13]
In [27]: map(None ,l2,l1)
Out[27]:
[(4, 2),
(5, 3),
(6, 4),
(7, 5),
(8, 6),
(9, 7),
(10, 8),
(11, 9),
(12, 10),
(13, 11)]
In [29]: def f3(x):
return x*3
In [30]: map (f3,l1)
Out[30]: [6, 9, 12, 15, 18,21, 24, 27, 30, 33]
reduce函数
In [32]: def f5(x,y):
....: return x +y
In [33]: reduce (f5,l2)
Out[33]: 85
In [34]: reduce (f5,l2,50)
Out[34]: 135
函数闭包
In [35]: def f1(x):
....: def f2(y):
....: return x**y
....: return f2
....:
In [36]: a1=f1(4)
In [37]: a1(2)
Out[37]: 16
深刻示例
In [51]: def f1(x,y):
def f2(m,n):
print "old (%d,%d),new(%d,%d)" %(x, y ,x+m ,y+n)
return f2
....:
In [52]: a1=f1(10,10)
In [53]: a1(2,7)
old (10,10),new (12,17)
生成器à遍历a**2 for a in range(1,11)
In [58]: for i in (a**2 for ain range(1,11)):
print i,
....:
1 4 9 16 25 36 49 64 81 100
生成器à转列表
In [59]: list(i**3 for i inrange(1,11))
Out[59]: [1, 8, 27, 64, 125,216, 343, 512, 729, 1000]
yield与生成器
In [60]: def genNum(x):
....: y=0
....: while y<=x :
....: yield y
....: y+=1
In [61]: g1=genNum(13)
In [62]: g1.next()
Out[62]: 0
In [63]: g1.next()
Out[63]: 1
生成器自身是可以迭代的
In [64]: def genNum(x):
....: i=1
....: while i<=x:
....: yield i**2
....: i+=1
In [70]: g1=genNum(6)
In [71]: for i in g1 :
print i,
....:
1 4 9 16 25 36
装饰器
带有参数的装饰器
递归
In [72]: def f1(x):
....: if x<=1:
....: return 1
....: else:
....: return x*f1(x-1)
....:
In [73]: f1(4)
Out[73]: 24
In [74]: f1(3)
Out[74]: 6
In [75]: f1(6)
Out[75]: 720
练习:实现费伯纳多数列
python类与面向对象
我的第一个python类
In [77]: class FirstClass():
....: data= "welcome my first class"
....: def printdata(self):
....: print self.data
In [79]: ins1= FirstClass() 实例化类
In [81]: ins1.data
Out[81]: 'welcome my firstclass'
In [82]: ins1.printdata()
welcome my first class
我的第二个
In [86]: class Second():
data= "Second"
def set(self,x):
self.str=x
def print1(self):
print self.str
....:
In [88]: a=Second()
In [89]: a.data
Out[89]: 'Second'
In [90]:a.set("haha")
In [91]: a.print1() 关键字不能让那个当类名
haha
方法构造器__init__
In [101]: class Myclass():
data= "hahahah 1 line"
def __init__(self,x):
self.str1=x
In [102]:a1=Myclass("LCL")
In [103]: a1.data
Out[103]: 'hahahah 1 line'
In [105]: a1.str1
Out[105]: 'LCL'
python父类的继承
In [106]: classPclass(object):
.....: gender="M"
.....: def __init__(self,who):
.....: self.name=who
.....:
In [107]: class Cclass(Pclass):
.....: def display (self):
.....: print self.gender,self.name
.....:
In [108]:a=Cclass("haha")
In [109]: a.display()
M haha
In [111]: a.gender
Out[111]: 'M'
In [112]: a.name
Out[112]: 'haha'
In [113]: dir(a) dir查看实例
Out[113]:
['__class__',
'__delattr__',
'__dict__',
'__doc__',
'__format__',
'__getattribute__',
'__hash__',
'__init__',
'__module__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'display',
'gender',
'name']
谁是谁的子类 判断!
In [115]: issubclass(Pclass,Cclass)
Out[115]: False
In [116]:issubclass(Cclass,Pclass)
Out[116]: True
In [117]:issubclass(Cclass,object)
Out[117]: True
这是不是你的实例
In [118]:isinstance(a,Cclass)
Out[118]: True
显示python默认的所有标准库模块
help("modules")
In [3]: import sys
In[5]: print sys.path
['','/usr/local/python27/bin', '/usr/local/python27/lib/python27.zip','/usr/local/python27/lib/python2.7', '/usr/local/python27/lib/python2.7/plat-linux2','/usr/local/python27/lib/python2.7/lib-tk','/usr/local/python27/lib/python2.7/lib-old','/usr/local/python27/lib/python2.7/lib-dynload','/usr/local/python27/lib/python2.7/site-packages', '/usr/local/python27/lib/python2.7/site-packages/IPython/extensions']
依次在以上路径寻找要导入的库文件
自定义模块路径
我自己/tmp下面写了一个py
#!/usr/bin/python27
#
x=30
def printInfo():
print x + 30
class MyClass():
data = "hello world!"
def __init__(self,who):
self.name=who
def printName(self):
print self.data,self.name
第一次尝试导入 import mymod 会报错
看一看当前的默认路径 print sys.path
sys.path.append("/tmp")
再试试尝试导入 import mymod 会报错
再看看当前的默认路径 print sys.path
ok
a=mymod.MyClass("LCL")
In [21]: a.printName()
hello world! LCL
单个让模块自我检测if __name__ =='__main__':
#!/usr/bin/python27
#
x=30
def printInfo():
print x + 30
class MyClass():
data = "hello world!"
def __init__(self,who):
self.name=who
def printName(self):
print self.data,self.name
if __name__ =='__main__':
printInfo()
ins1=MyClass("LCL")
print ins1.data
print ins1.name
[root@localhost tmp]# /tmp/mymod.py
60
hello world!
LCL
重新导入模块
In [23]: reload (mymod)
Out[23]: <module 'mymod'from '/tmp/mymod.py'>
制作模块包
mkdir –pv /tmp/pkg1
-rw-r--r-- 1 root root 0 May 16 07:47 __init__.py
-rwxr-xr-x 1 root root 320May 16 07:48 mymod2.py
__init__.py必须要有,可以是touch生成的空文件
导入包 In [24]: importpkg1.mymod2
看看包 In [28]: pkg1.mymod2.x
Out[28]: 34
python异常
举例
In[1]: try:
...: f1=open("/tmp/hello/123.txt")
...: except IOError,e:
...: print "haha Error",e
...:
haha Error [Errno 2] No such file or directory:'/tmp/hello/123.txt'
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recentcall last)
<ipython-input-2-05c9758a9c21>in <module>()
---->1 1/0
ZeroDivisionError:integer division or modulo by zero
----------------------------------------------------------------------------
ValueError
KeyError
IndexError
不发生异常 才执行else