Last active
December 16, 2022 14:09
-
-
Save rickowski/031342cb28bbf2b9c939 to your computer and use it in GitHub Desktop.
Python script to rename every file in a given folder to a random name, including the original file extension.
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
#!/usr/bin/python3 | |
# Copyright © 2015 Ole Rickowski | |
# This work is free. You can redistribute it and/or modify it under the | |
# terms of the Do What The Fuck You Want To Public License, Version 2, | |
# as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. | |
import os,sys,random,string | |
# Print help | |
def usage(): | |
print("randomrenamer: Renames every File in a given folder to a random string. The file extension is kept.") | |
print("Usage:", str(sys.argv[0]), "<Folder>") | |
# Print help if not executed correctly | |
def checkusage(): | |
if len(sys.argv) == 2 and os.path.isdir(str(sys.argv[1])): | |
dorename(correctpath(str(sys.argv[1]))) | |
else: | |
usage() | |
# Append / to path if not given | |
def correctpath(path): | |
if not path.endswith("/"): | |
path=path+"/" | |
return path | |
# Rename those files | |
def dorename(path): | |
print("Begin renaming...") | |
# Rename everything in target folder | |
for this in os.listdir(path): | |
print("Renaming:", this) | |
#Is target a file? | |
if os.path.isfile(path+this): | |
#Get a random name including the previous file extension | |
rand=createrandname(path,os.path.splitext(this)[1]) | |
#Do the rename | |
os.rename(path+this, path+rand) | |
print("\t->", rand) | |
else: | |
#Not a file | |
print("\tSkipped:", "'"+this+"'", "Target is not a file") | |
print("Finished!") | |
# Create a random file name and make sure the target file wouldn't exist | |
def createrandname(path,ext): | |
check=False | |
while check == False: | |
rand="".join(random.sample(string.ascii_lowercase+string.digits,20))+ext | |
check=True if not os.path.exists(path+rand) else False | |
return rand | |
# Check the usage and continue... | |
checkusage() |
The only problem I had on Mac was the copyright symbol on the 3rd line. If you replace the c-in-a-circle with (c), it should work.
(Thank you for the script, Ole. Saved me a bit of time today!)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm on a mac and trying to get this to work. What part of the above code needs changing? I have zero coding knowledge but I have a folder of 10,000 files that I'd like to assign random names to. Any insight on how to get this to work would be most appreciated!