Python的常用函数
get()
功能:给字典中的某个键对应的值赋予新值。
key:字典中要查找的键
default:当指定键不存在时,返回{key:default}。
dict.get(key, default=None)
operator.itemgetter()
功能:用于提取指定索引对应的值。
import operator
a = [1,2,3]
>>> b=operator.itemgetter(1) #用于提取索引为{1}的操作
>>> b(a)
2
>>> b=operator.itemgetter(1,0) #用于提取索引为{1,0}的操作
>>> b(a)
(2,1)
items()和iteritems()
dict.items():返回一个字典(键,值)对应的列表。
dict.iteritems():返回一个字典(键,值)对应的迭代器
(Note: iteritems() was removed in python3, so you can't use this method anymore.)。
dict={1:'one',2:'two',3:'three'}
>>> for k,v in dict.items():
... print("dict[%s] is %s" % (k,v))
...
dict[1] is one
dict[2] is two
dict[3] is three
对文件/文件夹的操作(os模块和shutil模块)
得到当前工作目录: os.getcwd()
更改当前工作目录:os.chdir()
返回指定目录下的所有文件和目录名:os.listdir("c:\python")
删除一个文件:os.remove()
删除多个目录:os.removedirs(r"c:\python")
判断是否是一个文件:os.path.isfile()
判断是否是一个目录:os.path.isdir()
判断是否是绝对路径:os.path.isabs()
判断给出的路径是否真存在:os.path.exists()
返回一个路径的目录名和文件名:os.path.split()
>>> os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
分离扩展名:os.path.splitext()
获取路径名:os.path.dirname()
获取文件名:os.path.basename()
获取文件大小:os.path.getsize(filename)
运行shell命令: os.system()
读取和设置环境变量:os.getenv()与os.putenv()
重命名:os.rename(old,new)
创建多级目录:os.makedirs(r"c:\python\test")
创建单个目录:os.mkdir("test")
获取文件属性:os.stat(file)
修改文件权限与时间戳:os.chmod(file)
终止当前进程:os.exit()
复制文件:shutil.copyfile("oldfile","newfile") #oldfile和newfile都只能是文件
复制文件:shutil.copy("oldfile","newfile") #oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
复制文件夹:shutil.copytree("olddir","newdir") olddir和newdir都只能是目录,且newdir必须不存在
删除目录:shutil.rmtree("dir") #空目录、有内容的目录都可以删