Created
March 24, 2019 22:27
-
-
Save LudwikJaniuk/5ab6b2b78d364916936e3dc2a45ec0e6 to your computer and use it in GitHub Desktop.
Add numerical ids to filename of every file in directory by renaming. Useful for zettelkasten.
This file contains hidden or 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
import os | |
import sys | |
import re | |
from pathlib import Path | |
# Run: python3 add_ids_in_filenames.py path_to_your_folder | |
# Behavior: Scans the folder, takes all files without an ID at the beginning | |
# consisting of 10 digits, and renames them all to add such an id to them. | |
# Ids are genrerated serially. | |
# Before renaming, checks for exact name collision not to overwrite something. | |
# Ignores already tagged files. | |
# Does not check for ID-collisions in already existing files. | |
# Useful for e.g. establishing a zettelkasten note system. | |
START_ID = 1 | |
ID_LEN = 10 | |
curr_id = START_ID | |
def pad(num): | |
s = str(num) | |
assert len(s) <= ID_LEN | |
zeros = "0"*(ID_LEN - len(s)) | |
return zeros + s | |
def next_id(): | |
global curr_id | |
ans = pad(curr_id) | |
curr_id += 1 | |
return ans | |
def main(): | |
if(len(sys.argv) != 2): | |
print("Need 2 args") | |
return | |
folder = sys.argv[1] | |
print("Gonna operate on folder: " + folder) | |
top, dirs, files = next(os.walk(folder)) | |
print(files) | |
to_process = [] | |
pat = re.compile("^\d{%d}" % ID_LEN) | |
for filename in files: | |
if pat.match(filename): | |
print(filename) | |
else: | |
to_process.append(filename) | |
for fn in to_process: | |
id = next_id() | |
new_name = id + " " + fn | |
old_path = Path(top, fn) | |
new_path = Path(top, new_name) | |
if new_path.exists(): | |
print("Skipping " + fn + " because of collision.") | |
continue | |
print("Want to rename " + str(old_path) + " to " + str(new_path)) | |
os.rename(old_path, new_path) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment