使用 string 和 string_2 正确打印字符串,但是当我想创建文件夹时,出现 [WinError 3] 错误:系统找不到正确的路径,mkdir 函数中的字符串突然有双 \
我的目标是根据当前日期创建一个文件夹
打印字符串时的结果
C:\Users\Albert\Desktop bc�3�3.06
C:\Users\Albert\Desktop bc�3�3.06
代码
import os
from datetime import datetime
import shutil
def archive_machine():
date=datetime.now()
date_correct_format = date.strftime('%Y-%m-%d')
date_correct_format_month = date.strftime('%Y.%m')
date_correct_format_year = date.strftime('%Y')
file_name = 'Sales Tracker - archived version' + date_correct_format
string = r'C:\Users\Albert\Desktop\abc'+'\\'+date_correct_format_year+'\\'+date_correct_format_month
string_2 = r'C:\Users\Albert\Desktop\abc'+f'\{date_correct_format_year}'+f'\\'+f'{date_correct_format_month}'
#print(string)
#print(string_2)
os.mkdir(string)
os.mkdir(string_2)
archive_machine()
以下内容对您有用吗? 基本上获取您想要传递的字符串(将 C:\Users\Desktop 位保留为标准,因为不想错误地创建另一个这样的目录!)并循环遍历它的每个元素以确保您拥有完整的目录路径已创建。
您可能需要先安装pathlib,如下所示
pip install pathlib
from pathlib import Path
from datetime import datetime
def path_check(dir_path,set_string):
def path_creation(dir_path):
# check if path given is currently a directory
# if it is move on, if not then create the directory passed
if Path(dir_path).is_dir():
print('directory already there')
else:
print('missing directory, creating now')
Path(dir_path).mkdir()
# holder for already made paths
made_paths = []
# loop through needed directories given in string
for s in dir_path.split(sep='\\'):
made_paths.append(s)
path_to_make = '\\'.join(made_paths)
path_creation(path_to_make)
def archive_machine():
date=datetime.now()
date_correct_format = date.strftime('%Y-%m-%d')
date_correct_format_month = date.strftime('%Y.%m')
date_correct_format_year = date.strftime('%Y')
file_name = f'Sales Tracker - archived version {date_correct_format}'
set_string = 'C:\\Users\\Albert\\Desktop\\'
string = f'abc\{date_correct_format_year}\{date_correct_format_month}'
path_check(string,set_string )
archive_machine()