Skip to content

Instantly share code, notes, and snippets.

@msoutopico
Created April 30, 2024 14:04
Show Gist options
  • Save msoutopico/41ecd0ccb1d8a10448aafc8033e86d38 to your computer and use it in GitHub Desktop.
Save msoutopico/41ecd0ccb1d8a10448aafc8033e86d38 to your computer and use it in GitHub Desktop.
foobar.py
#!/usr/bin/env python3
# preconditions
# touch foo.txt
# echo "foo" > foo.txt
# python foobar.py /path/to/foo.txt # no changes
# echo "bar" > foo.txt
# python foobar.py /path/to/foo.txt # will rename foo.txt to bar.txt
import sys
import os
from pathlib import Path
filepath = sys.argv[1]
# ex. /home/souto/foo.txt
filestem = Path(filepath).stem
parentdir = Path(filepath).parent
if not os.path.isfile(filepath):
print("file not found, nothing else to do")
sys.exit()
with open(filepath) as f:
content = f.read().strip()
if content != filestem:
print(f"Rename {filepath} to {parentdir}/{content}.txt")
os.rename(filepath, f"{parentdir}/{content}.txt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment