Skip to content

Instantly share code, notes, and snippets.

@taikedz
Last active April 13, 2026 09:32
Show Gist options
  • Select an option

  • Save taikedz/73b96c9fdf6a681fa627080a337cc8ad to your computer and use it in GitHub Desktop.

Select an option

Save taikedz/73b96c9fdf6a681fa627080a337cc8ad to your computer and use it in GitHub Desktop.
Add file number by creation date
#!/usr/bin/env python3
""" List files in order of time (see default for `ls -t`)
Add a numeric prefix to each file name.
If multiple folders are specified, the count restarts from one for each folder.
"""
import os
from pathlib import Path
import subprocess
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--execute", "-X", action="store_true", help="Actually perform the rename")
parser.add_argument("targets", nargs="+", help="Folders of files to rename")
args = parser.parse_args()
for target in args.targets:
target_p = Path(target)
command = "ls -tr".split()
command.append(target)
proc = subprocess.Popen(command , stdout=subprocess.PIPE, text=True)
stdout, _ = proc.communicate()
files = [target_p/f for f in stdout.split("\n") if f]
for i in range( len(files) ):
n = i+1
oldpath = files[i].absolute()
newpath = oldpath.parent / f"{str(n).zfill(3)}-{oldpath.name}"
print(f"{oldpath} --> {newpath}")
if args.execute:
os.rename(oldpath, newpath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment