python目录与文件名操作例子
1、操作目录与文件名
#!/usr/bin/envpython #-*-coding:utf-8-*- importos,re importshutil importtime
用listdir搜索
defsearch_OFD_old(my_pattern,diretory): try: names=os.listdir(diretory) exceptos.error: print"error" return fornameinnames: fullname=os.path.normpath(os.path.join(diretory,name)) ifos.path.isfile(fullname): result=my_pattern.search(name) ifresultandname.lower().endswith("txt"): shutil.copy(fullname,dest_dir) elifos.path.isdir(fullname): search_OFD(my_pattern,fullname)
用walk函数搜索
defsearch_OFD(my_pattern,diretory): forroot,dirs,filesinos.walk(diretory): forfilenameinfiles: result=my_pattern.search(filename) ifresultandfilename.lower().endswith("txt"): fullname=os.path.join(root,filename) shutil.copy(fullname,dest_dir)
目录不存在,则创建:
ifnotos.path.isdir(dest_dir): os.makedirs(dest_dir)
匹配名称
importre pattern=re.compile("1ABC") pattern.search(var)