Python常用函数的使用实例

获取当前文件夹下的所有文件: os.walk(dir)

# -*- coding: utf-8 -*-   
      
import os  
  
def file_name(file_dir):   
	for root, dirs, files in os.walk(file_dir):  
		print(root) #当前目录路径  
		print(dirs) #当前路径下所有子目录  
		print(files) #当前路径下所有非目录子文件
# -*- coding: utf-8 -*-   
  
import os  
  
def file_name(file_dir):   
	L=[]   
	for root, dirs, files in os.walk(file_dir):  
		for file in files:  
			if os.path.splitext(file)[1] == '.jpeg':  
				L.append(os.path.join(root, file))  
	return L  


#其中os.path.splitext()函数将路径拆分为文件名+扩展名
# -*- coding: utf-8 -*-  
import os  
  
def listdir(path, list_name):  #传入存储的list
	for file in os.listdir(path):  
		file_path = os.path.join(path, file)  
		if os.path.isdir(file_path):  
			listdir(file_path, list_name)  
		else:  
			list_name.append(file_path)

复制/移动文件: shutil.copyfile(oldf,newf), shutil.move(oldf,newf)

# -*- coding: utf-8 -*-
#!/usr/bin/python
#test_copyfile.py

import os,shutil

def mymovefile(srcfile,dstfile):
    if not os.path.isfile(srcfile):
        print("%s not exist!"%(srcfile))
    else:
        fpath,fname=os.path.split(dstfile)    #分离文件名和路径
        if not os.path.exists(fpath):
            os.makedirs(fpath)                #创建路径
        shutil.move(srcfile,dstfile)          #移动文件
        print("move %s -> %s"%( srcfile,dstfile))

def mycopyfile(srcfile,dstfile):
    if not os.path.isfile(srcfile):
        print("%s not exist!"%(srcfile))
    else:
        fpath,fname=os.path.split(dstfile)    #分离文件名和路径
        if not os.path.exists(fpath):
            os.makedirs(fpath)                #创建路径
        shutil.copyfile(srcfile,dstfile)      #复制文件
        print("copy %s -> %s"%( srcfile,dstfile))

srcfile='/Users/xxx/git/project1/test.sh'
dstfile='/Users/xxx/tmp/tmp/1/test.sh'

mymovefile(srcfile,dstfile)

删除文件夹

import shutil

shutil.rmtree(path)

创建文件夹

os.makedirs(dir)

文件是否存在

os.path.exists(f_path)

重命名文件

os.rename(f_old_name, f_new_name)

json的使用

import json

# json str 转 json对象
json_str = r'{"key1":"value1","key2":2}'
jd=json.loads(json_str)
print(jd)

# json 对象转 json str
print(json.dumps(jd))

以utf-8编码格式打开文件

f = open('a.txt', 'w', encoding='utf-8')

排序基础: sorted(listobj),  listobj.sort()

sorted([5, 2, 3, 1, 4])
输出[1, 2, 3, 4, 5]


a = [5, 2, 3, 1, 4]
a.sort()
a
输出[1, 2, 3, 4, 5]

插入排序

import sys  
   
def insert_sort(a):  
    ''''' 插入排序 
    有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数, 
    但要求插入后此数据序列仍然有序。刚开始 一个元素显然有序,然后插入一 
    个元素到适当位置,然后再插入第三个元素,依次类推 
    '''  
    a_len = len(a)  
    for i in range(a_len):
        key = a[i]
        j = i - 1
        while a_len = 0 and a[j] > key:  
            a[j+1] = a[j]  
            j-=1  
        a[j+1] = key  
    return a  
   
if __name__ == '__main__':  
    nums = [10,8,4,-1,2,6,7,3]  
    print 'nums is:', nums  
    insert_sort(nums)  
    print 'insert sort:', nums

批量重命名文件:os.listdir(dir), os.rename(oldf, newf)

# -*- coding: utf-8 -*-
import os;

def rename():
        i=0
        path="F:\test";
        filelist=os.listdir(path)#该文件夹下所有的文件(包括文件夹)
        for files in filelist:#遍历所有文件
            i=i+1
            Olddir=os.path.join(path,files);#原来的文件路径                
            if os.path.isdir(Olddir):#如果是文件夹则跳过
                    continue;
            filename=os.path.splitext(files)[0];#文件名
            filetype=os.path.splitext(files)[1];#文件扩展名
            Newdir=os.path.join(path,str(i)+filetype);#新的文件路径
            os.rename(Olddir,Newdir)#重命名
rename()

文件打开: open, try/finally, with

使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
一次性读取整个文件内容

# -*- coding: utf-8 -*-
import os;
file_object = open('thefile.txt')  
try:  
     all_the_text = file_object.read()  
finally:  
     file_object.close() 

但是每次都这么写实在太繁琐,所以,Python引入了with语句来自动帮我们调用close()方法:

with open('/path/to/file', 'r') as f:
    print(f.read())

文件打开编码: encoding

要读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件:
f = open('test.txt', 'r', encoding='gbk')
f.read()

遇到有些编码不规范的文件,你可能会遇到UnicodeDecodeError,因为在文本文件中可能夹杂了一些非法编码的字符。遇到这种情况,open()函数还接收一个errors参数,表示如果遇到编码错误后如何处理。最简单的方式是直接忽略:
f = open('test.txt', 'r', encoding='gbk', errors='ignore')
 

正则表达式: re.split()

使用正则表达式的re.split()方法,一次性拆分字符串

import re
 
s = "ab;cd|efg|hi,jkl|mn\topq;rst,uvw\txyz"
print re.split(r'[;|,\t]+',s)
 
输出:
['ab', 'cd', 'efg', 'hi', 'jkl', 'mn', 'opq', 'rst', 'uvw', 'xyz']

字典操作: dicobj.has_key(key), dicobj.keys, dicobj.items, dicobj[key], dicobj.clear()

# -*- coding: UTF-8 -*-
 
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
 
print "Value : %s" %  dict.has_key('Age')
del dict['Name']; # 删除键是'Name'的条目
dict.clear();     # 清空词典所有条目
del dict ;        # 删除词典

 

# -*- coding: UTF-8 -*-
a={1:'3', 'a':23, 5:654}
for k in dict.keys(a):
    print(k)
for v in dict.values(a):
    print(v)
for k,v in dict.items(a):
    #print(str(k)+":"+str(v))
    print("%s:%s"%(k,v))

判断数据类型: isinstance(obj, type)

# -*- coding: UTF-8 -*-
a=4
b='4'
c=True
print(isinstance(a,int))
print(isinstance(b,str))
print(isinstance(c,bool))

数据类型转换: str(num), int(str)

 

# -*- coding: UTF-8 -*-
a=5
b=str(a)
print(b)

c='67'
d=int(c)
print(d)

面向对象: class, __init__(self, args)

# -*- coding: UTF-8 -*-
 
class Employee:
   '所有员工的基类'
   empCount = 0
 
   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print("Total Employee %d" % Employee.empCount)
 
   def displayEmployee(self):
      print("Name : ", self.name,  ", Salary: ", self.salary)

if __name__ == '__main__':
    employee1=Employee('Tom',18000)
    employee2=Employee('Tina',20000)
    employee1.displayEmployee()
    employee2.displayEmployee()

多线程: thread, time.sleep(s), thread.start_new_thread(func, args[, kwargs])

# -*- coding: UTF-8 -*-
 
import thread
import time
 
# 为线程定义一个函数
def print_time(threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print ("%s: %s" % (threadName, time.ctime(time.time()) ))
 
# 创建两个线程
try:
   thread.start_new_thread( print_time, ("Thread-1", 2 ) )
   thread.start_new_thread( print_time, ("Thread-2", 4 ) )
except:
   print ("Error: unable to start thread")
 
while 1:
   pass

字符串: in, strobj.find(target)

site = 'http://www.sharejs.com/'
if "sharejs"  in site:
     print('site contains sharejs') 

s = "This be a string"
if s.find("is") == -1:
    print "No 'is' here!"
else:
    print "Found 'is' in the string."

 

列表推导式:​ [表达式 for 变量 in 列表]    或者  [表达式 for 变量 in 列表 if 条件]

 

def squared(x):
    return x*x
multiples = [squared(i) for i in range(30) if i % 3 is 0]
print multiples
#  Output: [0, 9, 36, 81, 144, 225, 324, 441, 576, 729]

字典推导式: { key_expr: value_expr for value in collection if condition }

mca={"a":1, "b":2, "c":3, "d":4}
dicts={v:k for k,v in mca.items()}
print dicts
# Output: {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

集合推导式: { expr for value in collection if condition }

跟列表推导式也是类似的。 唯一的区别在于它使用大括号{}

strings = ['a','is','with','if','file','exception']  
print {len(s) for s in strings}
# Output: set([1, 2, 4, 9]) 

lambda表达式(匿名函数)

lambda所表示的匿名函数的内容应该是很简单的,如果复杂的话,干脆就重新定义一个函数了,使用lambda就有点过于执拗了

func=lambda x:x+1
print(func(1))
#2
print(func(2))
#3

#以上lambda等同于以下函数

def func(x):
    return(x+1)

 

list1 = [3,5,-4,-1,0,-2,-6]
sorted(list1, key=lambda x: abs(x))
#等同于
list1 = [3,5,-4,-1,0,-2,-6]
def get_abs(x):
    return abs(x)
sorted(list1,key=get_abs)


filter() 函数

用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def is_odd(n):
    return n % 2 == 1
 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)

 

map()函数

map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回
map()函数不改变原有的 list,而是返回一个新的 list。

利用map()函数,可以把一个 list 转换为另一个 list,只需要传入转换函数

 

def f(x):
    return x*x
print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
输出结果:

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

获取脚本自身文件名: __file__, os.path.basename(f)

import os
f_name=os.path.basename(__file__).split('.')[0]

获取脚本所在的目录: __file__, os.path.dirname(f)

import os  
f_name=os.path.dirname(__file__)) 

 

执行系统命令: os.system

使用python 的os.system来执行系统命令

 

import os
print(os.system('ping www.baidu.com'))

os.system执行返回0表示成功,否则表示失败
 

os.popen() 方法用于从一个命令打开一个管道

通过os.popen()返回的是 file read 的对象,对其进行读取read()操作可以看到执行的输出
print(os.popen('echo "hello"').readline())
输出 hello

 

‘dict’ object has no attribute 'has_key'解决办法

Python3以后删除了has_key()方法

if dic.has_key(key1):

改为

if key1 in dic:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林新发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值