首页 > 解决方案 > 我不明白为什么我的文件路径为 os.makedir 格式不正确

问题描述

我正在尝试在 Windows 10 笔记本电脑上自学 Python。我刚刚读到了关于 os 库的章节。我已经为一个创建备份文件夹的简单程序编写了代码。但是,当我运行程序时,我收到错误:

OSError: [WinError 123] 文件名、目录名或卷标语法不正确:'C:\\Users\\Gareth Preston\\Documents\\Celtx\\Backup Wed Jun 24 14:22:55 2020'

所以我可以看到我正在尝试对 os.makedirs 使用无效路径,但我不明白为什么路径无效。我一直在查看 stackoverflow 的答案,我认为我使用 os.path.join 正确,但必须缺少一些东西。这是我的代码:

import os, shutil, time

root_src_dir = os.path.join('C:\\','Users','Gareth Preston','Documents','Celtx')
backup_folder_name = 'Backup ' + time.asctime()
root_dst_dir = os.path.join('C:\\','Users','Gareth Preston','Documents','Celtx',backup_folder_name)
   
for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)

    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        shutil.copy(src_file, dst_dir)

print(">>>>>>Backup Complete<<<<<<")

请问有人能告诉我我在误解什么吗?

标签: pythonwindowsoperating-systemos.path

解决方案


推荐阅读