Catz
Catz

Reputation: 25

Change filename for multiple files

I want to change filename for all my files in a folder. They all end with a date and time like "filename 2019-05-20 1357" and I want the date first for all files. How can I do that simplest way?

Upvotes: 0

Views: 306

Answers (3)

sahasrara62
sahasrara62

Reputation: 11228

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

Upvotes: 0

Anubhav Singh
Anubhav Singh

Reputation: 8699

Here is my Implementation:

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

Output Format:

20-05-2019 1749filename.ext

Upvotes: 0

philipp
philipp

Reputation: 51

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

Quick and roughly tested version

Upvotes: 2

Related Questions