我有一个函数,我想从用户那里得到一个路径作为输入,我想在路径中创建一个文件夹。
下面是代码片段: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文件/路径命名约定。具体地说,
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")