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

Dr.*_*ide 0 python path python-3.x python-os

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

这是代码片段:

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")
Run Code Online (Sandbox Code Playgroud)

我得到的错误输出是:

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'
Run Code Online (Sandbox Code Playgroud)

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

一点帮助将不胜感激。谢谢你

小智 6

我认为你的问题可能是冒号?请参阅Windows 文件/路径命名约定。具体来说,

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)
Run Code Online (Sandbox Code Playgroud)

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