Reputation: 756
How can I get Python to raise an exception on opening a file with an invalid file name? Example, I have this code
def write_html_to_file(set_name, pid, html_text):
if not os.path.exists(HTML_DUMP_DIR_NAME):
os.makedirs(HTML_DUMP_DIR_NAME)
path = (HTML_DUMP_DIR_NAME + set_name + '-' + pid + '.html')
try:
with open(path, "w+", encoding='utf-8') as html_dump_file:
html_dump_file.write(html_text)
except OSError as e:
logging.basicConfig(filename=LOG_FILE_PATH, level=logging.ERROR)
logging.error('Failed to create html dump. '
+ ' error=' + e
+ ' file_name=' + path)
Assume that the value of path is 'Folder1/SubFolder/Some Title: thing.html'
and the file does not exist yet.
What I expect is that Python will raise an OSerror
with Invalid Arguments, or something like that. What actually happens is it creates a file called 'Folder1/Subfolder/Some Title'
. Notice the filename stops at the invalid character
I know I can create my own exceptions that I can raise if I detect an invalid name, but in this case that's pointless. I only care if I'm trying to do something invalid at the OS level. It seems in this case its failing silently and I don't like that.
Edit: Sorry, I guess my question wasn't clear.
Upvotes: 1
Views: 2171
Reputation: 756
So it turns out (thanks eryksun), specifically the ':'
in the string you pass to open()
actually is a delimiter on NTFS systems that signifies that you want to write to multiple data streams:
My code works fine for any other character that is invalid in file names (*
for example). So the solution I came up with is to replace any ':'
in my filename with a -
before I pass it to open()
base_file_name= base_file_name.replace(':', '-')
':'
s are invalid in filenames anyway so this is fine for me.
Upvotes: 2