在用户给定路径中创建文件夹时出现 OSError PYTHON

OSError in creating folder in a user given path PYTHON

我有一个函数,我想从用户那里获取路径作为输入,我想在该路径中创建一个文件夹。

这是代码片段:

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")

我得到的错误输出是:

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'

我需要在给定的 parent_dir 中创建一个新的文件夹或目录,文件夹名称为 John_(date)_DATA

如果能提供一点帮助,我们将不胜感激。 谢谢你

我想你的问题可能是冒号?参见 Windows file/path naming conventions。具体来说,

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)

如果您重新格式化您的日期以替换 : 可以解决您的问题。

试试这个:

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")