python 批量修改栏目下面文件名称

版权声明:未经本人同意,禁止转载! https://blog.csdn.net/TianPingXian/article/details/80344059
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
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页