Created
September 6, 2023 16:12
-
-
Save najmam/4336ae85aa23ec556aeb8cc7ba334c45 to your computer and use it in GitHub Desktop.
Rename filenames from ISO-8859-1 to UTF-8, recursively
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
import os | |
import codecs | |
# Recursively rename files or folders from iso-8859-1 to utf-8 | |
def rename_to_utf8(directory, what): | |
for root, dirs, files in os.walk(directory): | |
for filename in (dirs if what == "dirs" else files): | |
old_path = os.path.join(root, filename) | |
# Decode the old filename from iso-8859-1 | |
try: | |
decoded_filename = bytearray(filename, 'iso-8859-1') | |
except UnicodeDecodeError: | |
print(f"Skipping file '{filename}' as it cannot be decoded from iso-8859-1") | |
continue | |
# Encode the filename in utf-8 | |
new_filename = decoded_filename.decode('utf-8') | |
# Construct the new file path | |
new_path = os.path.join(root, new_filename) | |
# Rename the file | |
try: | |
os.rename(old_path, new_path) | |
except UnicodeEncodeError: | |
print("Skipping "+old_path) | |
input_directory = "conversion" | |
rename_to_utf8(input_directory, "dirs") | |
rename_to_utf8(input_directory, "files") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment