Created
April 30, 2024 14:04
-
-
Save msoutopico/41ecd0ccb1d8a10448aafc8033e86d38 to your computer and use it in GitHub Desktop.
foobar.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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