0

I'm trying to create a folder that is valid according to the lib os in Windows.

# Replace <user>
filePath = r"C:\Users\<user>\AppData\Local\Temp\aux")
if not os.path.exists(filePath) and os.access(os.path.dirname(filePath), os.W_OK):
    os.makedirs(filePath)

But it failes with the following error

Traceback (most recent call last):
  File "C:\Users\<user>\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-8-a7b7e2731f40>", line 1, in <module>
    os.makedirs(filePath)
  File "C:\Users\<user>\Anaconda3\lib\os.py", line 221, in makedirs
    mkdir(name, mode)
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\Users\<user>\AppData\Local\Temp\aux'

The problem? You can't use "aux" as a folder name in Windows.

Is there a workaround in python to:

  • "Really" check if the folder is valid (the "if" in the code above is not enough)
  • Create the folder anyway?
Alechan
  • 817
  • 1
  • 10
  • 24
  • 2
    The way to check to see if the folder is valid is to try to create it, and handle the error. – kindall Mar 14 '19 at 18:09
  • 1
    In an other circumstance you might want to use [`exist_ok=True`](https://docs.python.org/3/library/os.html#os.makedirs). In your case however you want to know that it did not create the directory. – Bakuriu Mar 14 '19 at 18:13
  • 3
    DOS device names are reserved by user-mode code in the system runtime library, not by the filesystem driver in the kernel. So we can create a file or directory with a reserved DOS-device name by using a local-device path -- i.e. a fully-qualified path prefixed by "\\\\.\\" or "\\\\?\\". But it won't be accessible to programs that only support classic DOS paths. – Eryk Sun Mar 14 '19 at 18:26
  • [Here's a link to documentation for everything you could want to know about naming files/folders in Windows](https://learn.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file) – Maximilian Burszley Mar 14 '19 at 19:40

1 Answers1

1

In general, filesystem operations are where it's Easier to Ask for Forgiveness than Permission.

The best way to do this is to try to create the directory, catch the OSError if it fails, and then handle the failure.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135