python 学习总结

dir(类型) //dir(库)-->dir(os),dir(sys)
可用函数列表
help(函数名)
函数说明
import re ;re模块包含搜索,分割,替换等,正则表达式。
import os;
import sys;
import time;
一,python基本数据类型
数据:len();pow,abs,round int hex bin ;str();math.pi;math.sqrt(81);random.random();

字符串:(是序列) S='spam'; S[0]='s',S[3]='m'; S[-1]='m',S[-2]='a';
分片:S[1:]='pam',S[0:3]='spa';
加法=合并 S+'xyz'='spamxyz',S*4='spamspamspamspam'
S.find('pa')=1 返回偏移; S.replace('pa','XYZ')='sXYZm';
S.upper()='SPAM'; //lower
S.isalpha()=True; //isdigit
line= 'aaa,bbb,ccc,dd'
line.splite(',')=['aaa','bbb','ccc','dd'];
line.rstrip();//移除右边的空格
格式化 '%s,eggs,and %s' %('spam','SPAM!') ='spam,eggs,and SPAM!'
'{0},eggs,and {1}'.format('spam','SPAM!')='spam,eggs,and SPAM!'

列表:(是序列) L=[123,'spam',1.23];len(L)=3; l[0]=123,...
L.append('NI'); L.pop(2);L.sort();L.reverse()反转;
嵌套 M=[ [1,2,3],
[4,5,6],
[7,8,9]] ;M[0]=[1,2,3]; M[1][2]=6;
列表解析 col2=[row[1] for row in M]=[2,5,8];
[row[1]+1 for row in M]=[3,6,9];
[row[1] for row in M if row[1]%2==0]=[2,8];
[M[i][i] for i in [0,1,2]] = [1,5,9];
[c*2 for c in 'spam']=['ss','pp','aa','mm']
G=(sum(row) for row in M),next(G)=6,next(G)=15,next(G)=24;
list(map(sum,M))=[6,15,24];[ord(x) for x in 'spaam']={115,112,97,97,109}; 生成列表
{sum(row) for row in M}={6,15,24}; ...生成集合
{i:sum(M[i]) for i in range(3)}={0:6,1:15,2:24};...生成字典

字典:(是映射) D={'food':'spam','quantity':4,'color':'pink'}
D['food'] = 'spam';
D['quantity']+=1;D={'food':'spam','color':'pink','quantity':5}
D={};D['name']='Bob';D['job']='dev';D['age']=40;D={'age':40,'job':'dev','name':'Bob'}
嵌套 rec={'name':{'first':'Bob','last':'smith'},
'job':['dev','mgr'],
'age':40.5
}
D={'a':1,'b':2,'c':3};ks=list(D.keys())=['a','b','c'];
 
'f' in D = False
if not 'f' in D:
print('missing')
value=D.get('x',0) =0 ; D.get('b',0)=2
ks.sort()=['a','b','c']; 
for key in ks:
print(key,'=>',D[key]);
for key in sorted(D):
print(key,'=>',D[key]);
x=4
while x>0:
print('spam!'*4)
x-=1;

元组:(不可变的序列) T=(1,2,3,4);len(T)=4 ;T+(5,6)=(1,2,3,4,5,6);T[0]=1;
T.index(4)=3; T.count(4)=1;
T=('spam',3.0,[11,22,33]);

文件 f=open('data.txt','w');f.write('hello!\n');f.close();
f=file("/home/test/c.txt","r");
f.read();
date=open('data.bin','rb').read();
remove()/unlink() --- 删除文件
rename()/renames()---重命名文件
access()----------检验权限模式
chmod()-----------改变权限模式
chown()/lchown()-----改变 owner 和 group ID/功能相同, 但不会跟踪链接
umask()-------设置默认权限模式
open()---底层的操作系统 open (对于文件, 使用标准的内建 open() 函数)
read()/write()---根据文件描述符读取/写入数据
dup()/dup2()----复制文件描述符号,但是是复制到另一个文件描述符设备号
makedev()-----从 major 和 minor 设备号创建一个原始设备号
mkdir(path[,mode=0777])----创建目录
makedirs(name, mode=511)-----创建多层目录, 
rmdir(path)------删除目录
removedirs(path)----删除多层目录
listdir(path)----列出指定目录的文件
getcwd() --- ---返回当前工作目录
chdir(path)-----改变当前工作目录
walk(top,topdown=True, οnerrοr=None)---生成一个目录树下的所有文件名
chroot()----改变当前进程的根目录

集合  x=set('spam');x={'s','p','a','m'};
y={'h','a','m'};
x&y={'a','m'}; x|y={'a','p','s','h','m'};
x-y={'p','s'}

其它类型: 十进制数,分数,布尔值,占位符None

编程单元类型:
类:class worker://self是隐含的对象
def __init__(self,name,pay)://构造函数
self.name=name
self.pay=pay
def lastName(self):
return self.name.split()[-1];
def giveRaise(self,percent):
self.pay*=(1.0+percent)
与实现相关类型:

二,程序结构
以缩进代表程序结构;
(1)if语句:
if 表达式(expression1):    
    代码块1(if_suite)
elif 表达式2:
    代码块2
else:
    其他代码块(else-suite)
(2)while语句:
while 表达式:
    代码块
while(count<9):
print "the index is:", count
count+=1
(3)for语句:
for 迭代变量  in 迭代表:
    代码块
for x in range(1,10):
for y in range(1,x+1):
print str(y)+"*"+str(x)+"="+str(y*x),//默认输出换行,加逗号不换行
else:
print ;

函数:
函数通过def关键字定义的。以冒号作为函数体开始,return 返回
      形式为:def 标识符(参数): //形参
                 语句块,即函数体。
例如:def sayHello():
            print 'Hello World!' //语句块


      sayHello() //调用函数(实参)
变量:
全局变量:函数体外声明。函数内引用(重新赋值)要用global
局部变量
程序输入:  x=raw_input("please enter your name:");
程序输出: print "%s" %(num)
%s,%d,%s,%o(八进制),%h(十六制)

Lambda----用于创建一个匿名函数(没有函数名称的函数)
格式:fun() = lambda 变量 1 ,变量 2 , ... ,: 表达式
#!/usr/bin/python
def fun():
        a=1;b=2;n=6;m=3
        sum=lambda a,b:a+b
        sub=lambda n,m:n-m
        return sum(a,b)*sub(n,m)
print fun()


Generater生成器--生成器是一个带 yield 语句的函数。一个函数或者子
程序只返回一次,但一个生成器能暂停执行并返回一个中间的结果----那就是 yield 语句的功能,返回一个值给调用者并暂停执行。
当生成器的 next()方法被调用的时候,它会准确地从离开地方继续。
#!/usr/bin/python
def fun(n):
        for i in range(n):
                yield i
a=fun(3)
print a.next()
print a.next()
print a.next()


序列是通过索引来记录位置的
生成器是通过函数堆栈来记录位置的


常见函数:
abs()---返回数字的绝对值或者复数的模。
callable()--测试对象是否可调用,若可以,则返回真
cmp()---比较两个对象的值
divmod()---完成除法运算,返回除数和余数
isinstance()---测试对象的类型,用法为:isinstance(对象,对象类型)。
len()--返回字符串和序列的长度
range()--按参数生成有序的整数列表
xrange()--和range一样,只是节省了内存
round()---返回浮点数的四舍五入,用法:round(对象,保留小数点位数)
type()--返回对象的类型

内置的类型转换函数
chr()---把ASCII码转换为对应的字符串
ord()---把字符串转换成对应的ASCII码或者Unicode
hex()---把整数转换成十六进制
oct()---把整数转换成八进制

complex()--把字符串或数字转换为复数型
float()--把字符串或数字转换成浮点型
long()---把字符串或数字转换成长整型
int()----把字符串或数字转换成整型

list()---把序列对象转换成列表
str()----把序列对象转换成字符串
tuple()--把序列对象转换成元组

max()--返回给定参数的最大值
min()--返回给定参数的最小值
strftime()函数---实现从时间到字符串的转换。(import time)
strptime()函数---实现从字符串到时间的转换.(import time)
filter():它会把一个函数应用于序列中的每个项,并返回该函数返回真值时 的所有项,从而过滤掉返回假值的所有项。
#!/usr/bin/python
def nobad(s):
        return s.find("bad")==-1
s=["bad","good","bade","we"]
print filter(nobad,s)

map():把一个函数应用于序列中所有项,并返回一个列表。
#!/usr/bin/python
import string
s=["qi","mei","zhen"]
print map(string.capitalize,s)

zip()
reduce(fun,seq)

capitalize(string)--把字符串的首个字符替换成大字。
replace(string,old,new[,maxsplit])---字符串的替换函数,这里要注意的是,
maxsplit只是替换的次数;
a="qimeizhenqimeizhen";
print string.replace(a,"qimeizhen","jane")

split(string,sep=None,maxsplit=-1)--从string字符串中返回一个列表。
这个比较常用,强调两点:是以空格符为切片的,将字符串转换成列表,在进行分割

正则表达式:re模块
常见的特殊符号:
.  匹配任何字符(换行符除外)
^  匹配字符串的开始
$  匹配字符串的结尾
*  匹配前面出现的正则表达式零次或者多次
+  匹配前面出现的正则表达式一次或者多次
?  匹配前面出现的正则表达式零次或者一次
{N}  匹配前面出现的正则表达式N次
{M,N} 匹配前面出现的正则表达式M次到N次
[x-y] 匹配从x到y中的任意一个字符
常见的特殊字符:
\d  匹配任何数字【0-9】
\D  匹配非数字字符
\w  匹配字母,数字,下划线
\W  匹配不是字母,数字,下划线的字符
\s  匹配空白字符
\S  匹配不是空白的字符
\b  匹配单词的开始和结束
\B  匹配不是单词开始和结束的位置

模块:
模块创建--把相关的函数,代码或者类组织到一个文件中。
import 模块名 //查找顺序:当前目录,lib目录,site-packages目录
form module import func1,func2 //函数名

异常外理:
常见异常
AssertionError----断言语句失败
AttributeError----对象没有这个属性,试图访问一个对象没有的属性
IOError-----------输入/输出操作失败,基本是无法打开文件
ImportError-------无法引入模块或者包,基本是路径问题
IndentationError--语法错误,代码没有正确的对齐(缩进错误)
IndexError--------下标索引超出序列边界
KeyError----------试图访问你字典里不存载的键
KeyboardInterrupt-用户中断执行(ctrl+c)
NameError---------使用一个还未赋予对象的变量
SyntaxError-------Python 代码逻辑语法出错,不能执行
TypeError---------传入的对象类型与要求不符
UnboundLocalError-试图访问一个还未设置的全局变量
ValueError--------传入一个不被期望的值,即使类型正确


异常可以通过 try 语句来检测. 任何在 try语句块里的代码都会被监测,检查有无异常发生.
try 语句有两种主要形式: try-except 和 try-finally 
一个try语句可以对应一个或多个except子句, 
但只能对应一个finally子句, 或是一个try-except-finally 复合语句.
try:
p=open('ab','r')
except IOError,e:
print "no such file or directory"
except TypeError,e:
print "ab is string"
finally:
p.read();
...

raise 抛出异常

类:
使用 class 关键字定义一个类,并且类名的首字母要大写
类里面包含了变量和方法,这种包含也称之为“封装” 
class MyClass :
def __int__(self):     #定义一个对象的属性,初始化对象
self.var1="对象的属性1"
        self.var2="对象的属性2"
    属性定义(变量定义)
    方法定义(函数定义)

对象的创建:也就是类的实例化
myClass1 = MyClass()# 创建类的一个实例

#!/usr/bin/python
#encoding=utf-8

class Human:        #定义一个类
        name="qimeizhen"       #定义一个类的属性
        def run(self):         #定义一个类的方法(self类似于this指针)
                print "双腿来回跑"

a=Human()            #实例化一个类
print a.name         #通过实例化来调用类的属性
a.run()              #通过实例化来调用类的方法

继承:python在类名后使用一队括号来表示继承关系,括号中的类是父类。

  class Myclass(ParentClass1,ParentClass2)


样例:

一:拷贝文件

import os 
import os.path 
import shutil 
import time,  datetime

copycount=1
#把一个目录下的文件复制到指定目录中
def copyFiles(sourceDir,targetDir):

    global copycount
    for file in os.listdir(sourceDir):
        sourceFile = os.path.join(sourceDir,file)
        targetFile = os.path.join(targetDir,file)
        if os.path.isfile(sourceFile):
            print file
            print "copy file count: %d" %( copycount )
            if not os.path.exists(targetDir):  
                os.makedirs(targetDir)  
            #if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):
            #open(targetFile, "wb").write(open(sourceFile, "rb").read()) #速度较高,但内存占用太大,不适合大文件
            #shutil.copy(sourceFile,targetFile)  # 速度太慢
            src=sourceFile.replace('/','\\')
            dst=targetFile.replace('/','\\')
            os.system("copy %s %s" % (sourceFile,targetFile) ) #速度高
            copycount+=1
        else: #os.path.isdir(sourceFile):
            #print "false"
            First_Directory = False 
           # copyFiles(sourceFile, targetFile)
        #else:
        #    print "not parameter"

#删除一级目录下的所有文件
def removeFileInFirstDir(targetDir): 
    for file in os.listdir(targetDir): 
        targetFile = os.path.join(targetDir,  file) 
        if os.path.isfile(targetFile): 
            os.remove(targetFile)

#复制一级目录下的所有文件
def coverFiles(sourceDir,  targetDir): 
        for file in os.listdir(sourceDir): 
            sourceFile = os.path.join(sourceDir,  file) 
            targetFile = os.path.join(targetDir,  file) 
            #cover the files 
            if os.path.isfile(sourceFile): 
                open(targetFile, "wb").write(open(sourceFile, "rb").read())
#复制指定文件到目录
def moveFileto(sourceDir,  targetDir): 
     shutil.copy(sourceDir,  targetDir)

#向指定目录下写文件
def writeVersionInfo(targetDir): 
     open(targetDir, "wb").write("Revison:")

#返回当前时间,以便创建指定目录时使用
def getCurTime(): 
    nowTime = time.localtime() 
    year = str(nowTime.tm_year) 
    month = str(nowTime.tm_mon) 
    if len(month) < 2: 
        month = '0' + month 
    day =  str(nowTime.tm_yday) 
    if len(day) < 2: 
        day = '0' + day 
    return (year + '-' + month + '-' + day)	 

#主函数
if  __name__ =="__main__": 
    print "Start(S) or Quilt(Q) \n" 
    flag = True 
    while (flag): 
        answer = raw_input() 
        if  'S' == answer:
            flag = False 
            formatTime = getCurTime()
			#targetFoldername = "Build " + formatTime + "-01"
           # Target_File_Path= 'Y:/1/ '
            #Target_File_Path += targetFoldername  
            sourceDIR="D:/vmos/fc19/"
            targetDIR="Y:/1/"
            copyFiles(sourceDIR,targetDIR)
            #removeFileInFirstDir(Target_File_Path)
            #coverFiles(Release_File_Path,  Target_File_Path)
            #moveFileto(Firebird_File_Path,  Target_File_Path) 
            #moveFileto(AssistantGui_File_Path,  Target_File_Path) 
            #writeVersionInfo(Target_File_Path+"\\ReadMe.txt") 
            print "all sucess" 
        else: 
            print "not the correct command"


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值