pythonmkdir语法错误_Python:windows创建文件夹时出错操作系统.mkdir使用方括号

在Windows上,当我试图创建以下文件夹时:os.mkdir('H:\\__ Photos\\____Photos to be sorted\\[ Photo sorting process ]\\_NEW\\__PROC_PHOTOS\\1. Original CRW')

我得到了一个错误:WindowsError: [Error 3] The system cannot find the path specified: 'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\1. Original CRW'

“新建”文件夹已存在,它是当前工作目录。然后我试着用一个反斜杠:

^{pr2}$

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\x01. Original CRW'

所以“\1”被转换成了“\x01”。转义这个特定的反斜杠会导致[Error 3]错误,如前所述。在

使字符串成为字符串文字:os.mkdir(r'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\1. Original CRW')

产生了相同的错误:WindowsError: [Error 3] The system cannot find the path specified: 'H:\__ Photos\____Photos to be sorted\[ Photo sorting process ]\_NEW\__PROC_PHOTOS\1. Original CRW'

然后:os.mkdir("H:\[ Photo sorting process ]\\NEW")

错误(“[照片排序过程]”不存在),但是:os.mkdir("H:\[ Photo sorting process ]")

os.mkdir("H:\[ Photo sorting process ]\\NEW")

很好。这是否意味着我只能创建1级子目录?还有别的办法吗?我想把路径作为变量传递。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,使用`mkdir()`和`makedirs()`函数可以创建一个新的目录。其中,`mkdir()`函数用于创建单个目录,而`makedirs()`函数则可以创建多个目录。 下面是使用`mkdir()`函数创建单个目录的示例代码: ```python import os # 创建单个目录 os.mkdir('/path/to/new/folder') ``` 在使用`mkdir()`函数时,需要注意以下几点: 1. 如果目录已经存在,调用`mkdir()`函数会抛出`FileExistsError`异常。因此,在创建目录之前,可以先判断目录是否存在,例如: ```python if not os.path.exists('/path/to/new/folder'): os.mkdir('/path/to/new/folder') ``` 2. 使用`mkdir()`函数只能创建单个目录,如果要创建多层嵌套的目录,需要多次调用`mkdir()`函数。 相比之下,`makedirs()`函数可以一次性创建多层嵌套的目录。例如: ```python import os # 创建多层嵌套的目录 os.makedirs('/path/to/new/folder') ``` 在使用`makedirs()`函数时,需要注意以下几点: 1. 如果目录已经存在,`makedirs()`函数不会抛出异常,而是直接返回。 2. 如果同时有多个线程或进程调用`makedirs()`函数创建同一个目录,可能会发生竞争条件,导致创建失败或者创建出错的目录。因此,在多线程或多进程环境下,应该使用线程安全的方式创建目录。可以通过`os.makedirs()`函数的`exist_ok`参数来实现线程安全创建目录,例如: ```python import os import threading # 线程安全创建目录 lock = threading.Lock() def create_dir(path): with lock: os.makedirs(path, exist_ok=True) t1 = threading.Thread(target=create_dir, args=('/path/to/new/folder',)) t2 = threading.Thread(target=create_dir, args=('/path/to/new/folder',)) t1.start() t2.start() t1.join() t2.join() ``` 在上述代码中,使用了`threading.Lock()`来保证同一时刻只有一个线程调用`os.makedirs()`函数创建目录。并且,在`os.makedirs()`函数中设置了`exist_ok=True`参数,表示如果目录已经存在,不会抛出异常,而是直接返回。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值