对于使用 Python 创建新文件夹,步骤如下:导入 os 模块。使用 os.makedirs() 函数传递文件夹路径。处理错误,使用 try 和 except 语句捕获 OSError 异常。检查文件夹是否存在,使用 os.path.exists() 函数避免 FileExistsError 异常。

如何使用 Python 建立新文件夹
在 Python 中,可以使用 os 模块来创建新文件夹。以下是在 Python 中建立新文件夹的步骤:
导入 os 模块。
<code class="python">import os</code>
使用 os.makedirs() 函数。
立即学习“Python免费学习笔记(深入)”;
os.makedirs() 函数用于创建目录(文件夹),包括不存在的父目录。要创建新文件夹,请将文件夹的路径作为参数传递给 os.makedirs() 函数。
<code class="python">os.makedirs('new_folder')</code>这将在当前工作目录中创建名为 new_folder 的文件夹。
处理错误。
如果创建文件夹时出现错误,os.makedirs() 函数将引发 OSError 异常。为了处理此错误,可以使用 try 和 except 语句。
<code class="python">try:
os.makedirs('new_folder')
except OSError as error:
print(error)</code>检查文件夹是否存在。
如果文件夹已经存在,os.makedirs() 函数将引发 FileExistsError 异常。为了避免此错误,可以使用 os.path.exists() 函数来检查文件夹是否存在,然后再尝试创建它。
<code class="python">if not os.path.exists('new_folder'):
os.makedirs('new_folder')</code>以上就是python如何建立新文件夹的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号