import os
import re
import shutil
def renameFile(path, postfix=None):
os.chdir(path)
fileRegex = re.compile(r'(\d{4})-(\d{1,2})-(\d{1,2})')
fileList = os.listdir(path)
endFileList = []
for filename in fileList:
if filename.endswith('.' + postfix) and fileRegex.search(filename):
fileSearch = fileRegex.search(filename).groups()
rename = shutil.move(filename, fileSearch[2] + '-' + fileSearch[1] + '-' + fileSearch[0] + '.' + postfix)
endFileList.append(rename)
return endFileList
path = '/www/wwwpython/test/x/datatxt/'
print(renameFile(path, 'txt'))
def createFile(path):
for x in range(100):
file = open(path + '2018-05-' + str(x) + '.txt', 'w')
file.write('My name is wsg {0}'.format(x))
createFile('/www/wwwpython/test/x/datatxt/')
def renameFile(path, postfix=None):
os.chdir(path)
fileRegex = re.compile(r'(\d{4})-(\d{1,2})-(\d{1,2}).'+postfix+'')
fileList = os.listdir(path)
endFileList = []
for filename in fileList:
search =fileRegex.search(filename)
if search:
fileSearch = search.groups()
rename = shutil.move(filename, fileSearch[2] + '-' + fileSearch[1] + '-' + fileSearch[0] + '.' + postfix)
endFileList.append(rename)
return endFileList
更简洁写法
def renameFile(path, postfix=None):
os.chdir(path)
fileList = os.listdir('.')
endFileList = []
for filename in fileList:
search =re.match(r'(\d{4})-(\d{1,2})-(\d{1,2}).'+postfix,filename)
if search:
fileSearch = search.groups()
rename = shutil.move(filename, fileSearch[2] + '-' + fileSearch[1] + '-' + fileSearch[0] + '.' + postfix)
endFileList.append(rename)
return endFileList