更改多个文件的文件名

时间:2019-05-20 12:01:10

标签: python

我想更改文件夹中所有文件的文件名。它们都以日期和时间结尾,例如“ filename 2019-05-20 1357”,我希望所有文件的日期都优先。我该怎么做最简单的方法?

3 个答案:

答案 0 :(得分:2)

#!/usr/bin/python3

import shutil, os, re

r = re.compile(r"^(.*) (\d{4}-\d{2}-\d{2} \d{4})$")

for f in os.listdir():
    m = r.match(f)
    if m:
        shutil.move(f, "{} {}".format(m.group(2), m.group(1)))

经过粗略测试的快速版本

答案 1 :(得分:0)

import os
import re
import shutil

dir_path = '' # give the dir name

comp = re.compile(r'\d{4}-\d{2}-\d{2}')
for file in os.listdir(dir_path):
    if '.' in file:
        index = [i for i, v in enumerate(file,0) if v=='.'][-1]
        name = file[:index]
        ext = file[index+1:]
    else:
        ext=''
        name = file
    data = comp.findall(name)  
    if len(data)!=0:
        date= comp.findall(name)[0]

        rest_name = ' '.join(comp.split(name)).strip()
        new_name = '{} {}{}'.format(date,rest_name,'.'+ext)
        print('changing {} to {}'.format(name, new_name))
        shutil.move(os.path.join(dir_path,name), os.path.join(dir_path, new_name))
    else:
        print('file {} is not change'.format(name))

答案 2 :(得分:0)

这是我的实现方式

from datetime import datetime
import os

path = '/Users/name/desktop/directory'
for _, file in enumerate(os.listdir(path)):
    os.rename(os.path.join(path, file), os.path.join(path, str(datetime.now().strftime("%d-%m-%Y %H%M"))+str(file)))

输出格式:

20-05-2019 1749filename.ext