Nicolas Telmaut
Nicolas Telmaut

Reputation: 11

How to sort a list by creation date? (Python - OS library)

I'd like to rename a list of video cuts in a folder (in my case /Desktop/Cuts/) from: xxx.mp4, yyy.mp4, ..., zzz.mp4 to: 1.mp4, 2.mp4, ..., 33.mp4.

1.mp4 will be the video that was first created in the folder. 2.mp4 will be the second, etc.

What I am doing now (please see code below) renames the video cuts in /Cuts/, but according to an order that I don't understand, and that is definitely NOT creation date. (it does not seem alphabetical, either)

import os
path = '/Users/ntelmaut/Desktop/Cuts/'

i = 1
for file in os.listdir(path):

    new_file_name = "{}.mp4".format(i)
    os.rename(path + file, path + new_file_name)

    #print path + file
    i = i+1 

I have tried make a variable out of os.listdir(path) and to apply sorted() function, but to no avail yet (I am a newbie to Python - sorry).

Would love a pointer, here.

Thank you!

Upvotes: 1

Views: 309

Answers (2)

Lovleen Kaur
Lovleen Kaur

Reputation: 342

Solution

import glob

import os
dirpath = '/Users/ntelmaut/Desktop/Cuts/'

files = glob.glob(os.path.join(path, '*.mp4'))   
files.sort(key=os.path.getmtime)

for i, filename in enumerate(files, 1):
    try:
       os.rename(filename, "{0}.mp4".format(i))
    except OSError as e:
       print("OSError: ", e)

Upvotes: 1

gold_cy
gold_cy

Reputation: 14216

If I understand correctly this is what you want.

import os
path = '/Users/ntelmaut/Desktop/Cuts/'

def sort_key(file):
    return os.stat(file).st_ctime

files = os.listdir(path)
sorted_files = sorted((os.path.join(path, f) for f in files), key=sort_key)

i = 1
for file in sorted_files:
    new_file_name = f"{i}.mp4"
    os.rename(file, new_file_name)
    i += 1

A cleaner way would be to use the pathlib module.

from pathlib import Path

p = Path('/Users/ntelmaut/Desktop/Cuts/')

def sort_key(path):
    return path.stat().st_ctime

sorted_files = sorted(p.iterdir(), key=sort_key)

for idx, file in enumerate(sorted_files, 1):
    new_name = f"{idx}.mp4"
    file.rename(p / new_name)

Upvotes: 0

Related Questions