Home > Enterprise >  How to sort files by time and also rename them?
How to sort files by time and also rename them?

Time:02-23

I want to get all files (.txt) in a directory, sorted by time and then get renamed like name1,name2,... using python

Here's what I tried:

import os
def rename (directory):
    os.chdir(directory)  
    result = sorted (filter (os.path.isfile, os.listdir('.')), key-os.path.getmtime)
        ('\n'.join(map(str, result)))
        os.rename (name, "0" name)

path=input("Enter the file path")
rename(path)

CodePudding user response:

here is one way to do so:

def rename(directory):
    os.chdir(directory)
    num = 1
    for file in [file for file in sorted(os.listdir(), key=os.path.getctime) if os.path.splitext(file)[1] == ".txt"]:
        if os.path.splitext(file)[1] == ".txt":
            os.rename(file, f"name{num}.txt")
            num  = 1

We used sorted() to sort files by last modified date, using os.path.getctime()

To get the extension of the file, we used os.path.splitext().

  • Related