更改多个文件的文件名

2024-04-25 23:15:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想更改文件夹中所有文件的文件名。它们都以日期和时间结束,比如“filename 2019-05-20 1357”,我希望所有文件的日期都排在第一位。我怎么能用最简单的方法呢?你知道吗


Tags: 文件方法文件夹文件名时间filename
3条回答

以下是我的实现:

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
#!/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)))

快速粗略测试版本

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))

相关问题 更多 >