I'm trying to write a Python script to recursively search a folder and process its contents. It fails because some subfiles and subfolders have a special character in their names: '' I've looked at this character in a hex editor and it shows up as byte 0x00. In Windows, when I try to use this character in a filename, it lets me and doesn't complain that it is invalid (it shows up as a '.' floating at mid-height)
I've written a small script and a dummy folder testDir to demonstrate the issue:
It causes the error: WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: '../with_special_chars/testDir?/.'
import os
root_directory = r"../with_special_chars/"
def explore_folder(root_directory):
for filename in os.listdir(root_directory):
fullpath = os.path.join(root_directory, filename)
print(fullpath)
print(os.path.isdir(fullpath))
print(os.path.exists(fullpath))
if os.path.isfile(fullpath):
print(fullpath)
else:
explore_folder(fullpath)
explore_folder(root_directory)
The output of the program before it prints the error is:
../with_special_chars/testDir?
False
False
It seems that Python is failing to read the directory because the special character is replaced with a '?' and then the resulting path is no longer recognized as a valid path. Is there a workaround for this? I would like to avoid having to change many file and directory names