Last active
May 8, 2020 22:32
-
-
Save thieu1995/0b7778eed6d42b267c14ead17963a5f9 to your computer and use it in GitHub Desktop.
Rename your files in input folder cross platform between linux and windows.
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
### Thieu Nguyen (https://www.researchgate.net/profile/Thieu_Nguyen6) | |
import os | |
import sys | |
import re | |
exclude_folders = [".git", "LICENSE", ".gitignore"] | |
chars_to_remove = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", ":", ",", "<", ">", ";", "+", "|"] | |
regular_expression = '[' + re.escape(''.join(chars_to_remove)) + ']' | |
def _rename_files_(path_to_folder=None): | |
if not os.path.isabs(path_to_folder): # if your path is absolute | |
current_directory = os.getcwd() | |
path_to_folder = os.path.join(current_directory, path_to_folder) | |
for fname in os.listdir(path_to_folder): | |
exclude_check = any(ef in fname for ef in exclude_folders) | |
if exclude_check: # Dont rename files in exclude folders | |
continue | |
full_path = os.path.join(path_to_folder, fname) | |
if os.path.isfile(full_path): # checks if path is a file | |
non_ascii = fname.encode("ascii", "ignore") | |
fname = non_ascii.decode() # Removed all non-ascii characters | |
fname = re.sub(regular_expression, '', fname) # Removed all special characters | |
fname = fname.replace("_", "-") # Replaced _ by - | |
filename, file_extension = os.path.splitext(fname) # Get extension | |
tokens_list = filename.split() # Create tokens | |
fname = " ".join([word.strip().capitalize() for word in tokens_list]) | |
filename = fname + file_extension # Join filename and its extension | |
new_path = os.path.join(path_to_folder, filename) | |
os.rename(full_path, new_path) | |
elif os.path.isdir(full_path): | |
_rename_files_(full_path) | |
else: | |
print("ERROR: Not a folder or file!") | |
if __name__ == '__main__': | |
# Calling main() function | |
path_to_folder = sys.argv[1] | |
if path_to_folder is not None: | |
_rename_files_(path_to_folder) | |
else: | |
print("Need argument for your path_to_folder!!! Something like this: python main.py 'test_folder' !!!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment