- #!/usr/bin/env python
- #coding=utf-8
- import os
- import re
- import shutil
- #修改目录下文件名
- def TestRename(Dir):
- for files in os.listdir("d:/work"):
- if files =='tester.log':
- filePath = os.path.join( Dir, files )
- print filePath
- os.rename(os.path.join('d://work',files), os.path.join('d://work','1.log'))
- #删除目录下所有文件
- def CleanDir( Dir ):
- if os.path.isdir( Dir ):
- paths = os.listdir( Dir )
- for path in paths:
- filePath = os.path.join( Dir, path )
- if os.path.isfile( filePath ):
- try:
- os.remove( filePath )
- except os.error:
- autoRun.exception( "remove %s error." %filePath )#引入logging
- elif os.path.isdir( filePath ):
- if filePath[-4:].lower() == ".svn".lower():
- continue
- shutil.rmtree(filePath,True)
- return True
- #正则删除文件
- def grem(path, pattern):
- pattern = re.compile(pattern)
- for each in os.listdir(path):
- if pattern.search(each):
- name = os.path.join(path, each)
- try: os.remove(name)
- except:
- grem(name, '')
- os.rmdir(name)
- #正则删除文件夹中子文件夹中的文件
- def DelFileAll(Dir,pattern):
- tem=os.walk(Dir)
- pattern = re.compile(pattern)
- for i,j,k in tem:
- for n in k:
- if pattern.search(n):
- name = i+os.sep+n
- try: os.remove(name)
- except:
- grem(name,'')
- os.rmdir(name)
- #复制文件
- def copyfiles(Dir):
- tem=os.walk(Dir)
- for i,j,k in tem:
- for n in k:
- name = i+os.sep+n
- print name
- shutil.copyfile(name,name+'_2.gif')
- shutil.copyfile(name,name+'_3.gif')
- if __name__ == '__main__':
- copyfiles('D:/work')
- #grem('D:/work/romantic','_[0-9]+.gif')
- print 'ok'
python 文件操作
最新推荐文章于 2021-12-08 16:08:23 发布