Search code examples
pythonpython-3.xpathpython-os

OSError in creating folder in a user given path PYTHON


I am having a function in which I want to get a path from the user as input and I want to create a folder in the path.

Here is the code snippet:

import os
import datetime

def create_folder(name)
    current_time = datetime.datetime.now()
    folder_name = str(name)+"_("+str(current_time)+")_DATA"
    parent_dir = directory_var.get()        #getting value from tkinter
    print(folder_name)
    print(parent_dir)
    path = os.path.join(parent_dir, folder_name)
    os.mkdir(path)

create_folder("John")

The output with error I am getting is :

John_(2021-08-05 23:43:27.857903)_DATA
C:\app_testing

os.mkdir(path)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 
'C:\\app_testing\\John_(2021-08-05 23:43:27.857903)_DATA'

I need to create a new folder or directory in the given parent_dir with folder name as John_(date)_DATA


Solution

  • I think your problem may be the colons? See Windows file/path naming conventions. Specifically,

    Use any character in the current code page for a name, including 
    Unicode characters and characters in the extended character set 
    (128–255), except for the following:
    
    The following reserved characters:
    
    < (less than)
    > (greater than)
    : (colon)
    " (double quote)
    / (forward slash)
    \ (backslash)
    | (vertical bar or pipe)
    ? (question mark)
    * (asterisk)
    

    If you reformat your date to replace the : that could solve your issue.