0

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

0

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

import os
import datetime
from time import strftime


def create_folder(name):
    current_time = datetime.datetime.now()
    x = current_time.strftime('%Y/%m/%d %H.%M.%S')  # You choose the format!
    folder_name = str(name)+"_("+str(x)+")_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")

4 Comments

Forward slashes are just as bad as colons from a Windows perspective.
As I said: 'You choose the format!'; maybe I wasn't clear enough
Yes, you did, but novices have a way of blindly pasting code without bothering to read such comments. Better not to wrong-foot a beginner by presenting an example you know (or ought to know) won't work. OP would not have asked the question if he knew about the rules for Windows filenames.
Sorry, I didn't make it clear that the answer was just an example of what he could do to change the format; thanks for the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.