参考链接: os.mkdir(path, mode=0o777, *, dir_fd=None)
参考链接: os.makedirs(name, mode=0o777, exist_ok=False)
参考链接: os.path.exists(path)
实验1,创建文件夹,单级目录:
import os
folderPath = r'b'
os.mkdir(folderPath)
运行效果:
实验2,递归创建文件夹,多级目录:
import os
folderPath = r'c/d/e'
os.makedirs(folderPath)
运行效果:
实验3,创建单级目录,但目录已存在:
import os
folderPath = r'b'
os.mkdir(folderPath)
程序报错:
Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。
尝试新的跨平台 PowerShell https://aka.ms/pscore6
加载个人及系统配置文件用了 896 毫秒。
(base) PS C:\Users\chenxuqi\Desktop\News4cxq\my-experiments> conda activate pytorch_1.7.1_cu102
(pytorch_1.7.1_cu102) PS C:\Users\chenxuqi\Desktop\News4cxq\my-experiments> & 'D:\Anaconda3\envs\pytorch_1.7.1_cu102\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2021.1.502429796\pythonFiles\lib\python\debugpy\launcher' '50361' '--' 'c:\Users\chenxuqi\Desktop\News4cxq\my-experiments\test.py'
Traceback (most recent call last):
File "c:\Users\chenxuqi\Desktop\News4cxq\my-experiments\test.py", line 3, in <module>
os.mkdir(folderPath)
FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'b'
(pytorch_1.7.1_cu102) PS C:\Users\chenxuqi\Desktop\News4cxq\my-experiments>
实验4,创建多级目录,但目录已存在:
import os
folderPath = r'c/d/e'
os.makedirs(folderPath)
程序报错:
Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。
尝试新的跨平台 PowerShell https://aka.ms/pscore6
加载个人及系统配置文件用了 854 毫秒。
(base) PS C:\Users\chenxuqi\Desktop\News4cxq\my-experiments> conda activate pytorch_1.7.1_cu102
(pytorch_1.7.1_cu102) PS C:\Users\chenxuqi\Desktop\News4cxq\my-experiments> & 'D:\Anaconda3\envs\pytorch_1.7.1_cu102\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2021.1.502429796\pythonFiles\lib\python\debugpy\launcher' '50278' '--' 'c:\Users\chenxuqi\Desktop\News4cxq\my-experiments\test.py'
Traceback (most recent call last):
File "c:\Users\chenxuqi\Desktop\News4cxq\my-experiments\test.py", line 3, in <module>
os.makedirs(folderPath)
File "D:\Anaconda3\envs\pytorch_1.7.1_cu102\lib\os.py", line 223, in makedirs
mkdir(name, mode)
FileExistsError: [WinError 183] 当文件已存在时,无法创建该文件。: 'c/d/e'
(pytorch_1.7.1_cu102) PS C:\Users\chenxuqi\Desktop\News4cxq\my-experiments>
实验5,创建单级目录之前先做判断
import os
folderPath = r'b'
if not os.path.exists(folderPath):
os.mkdir(folderPath)
实验6,创建多级目录之前先做判断
import os
folderPath = r'c/d/e'
if not os.path.exists(folderPath):
os.makedirs(folderPath)