Luke Luke - 1 year ago 91
Python Question

Python OSError while attempting os.mkdir

import os
directory=input("Directory: ")
if not os.path.exists(directory):

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.

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 Source


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


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.