Luke Luke - 6 months ago 26
Python Question

Python OSError while attempting os.mkdir

import os
directory=input("Directory: ")
if not os.path.exists(directory):
os.mkdir(directory)
os.mkdir(str(directory)+'\steamCMD')
os.mkdir(str(directory)+'\temporary')


A snippet from my code. Returns OSError on the last line shown here. Why? Does exactly same thing as 5th line yet 5th line works like a charm.
Error:

os.mkdir(str(directory)+'\temporary')
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'c:\\testing\temporary'


Similar: Python - os.rename() - OSError: [WinError 123]
os.mkdir(path) returns OSError when directory does not exist
However he had different mistake to me. Anyone tell me why this is happen?

Answer

Try:

os.mkdir(str(directory) + '\\temporary')

Or

os.mkdir(str(directory) + r'\temporary')

About the two \\ or r'\temporary', here is the documentation and here is a good question.


Also, os.path.join() is a good choice because which uses \\ on Windows but / on *nix. For example:

os.mkdir(os.path.join(directory), 'temporary')

This gives directory\temporary on Windows and directory/temporary on *nix. It is a more clear and simple way.

Comments