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.
- I do want it to create a file, that part I'm happy about.
- The problem is that the file-name that gets created stops at the invalid character. I want the entire name to be there.
- My question is, Why doesn't python raise an exception so I can handle it when it encounters an invalid character