新建文件夹 Python
时间: 2023-12-25 15:28:56 浏览: 28
以下是使用Python创建文件夹的示例代码:
```python
import os
# 创建一级文件夹
folder_name = "new_folder"
os.mkdir(folder_name)
```
这段代码使用了`os.mkdir()`函数来创建一级文件夹。你可以将`folder_name`替换为你想要创建的文件夹的名称。执行这段代码后,将会在当前工作目录下创建一个名为`new_folder`的文件夹。
如果你想要创建多级文件夹,可以使用`os.makedirs()`函数。示例如下:
```python
import os
# 创建多级文件夹
folder_path = "parent_folder/child_folder"
os.makedirs(folder_path)
```
这段代码使用了`os.makedirs()`函数来创建多级文件夹。你可以将`folder_path`替换为你想要创建的文件夹的路径。执行这段代码后,将会在当前工作目录下创建一个名为`parent_folder`的父文件夹,并在其中创建一个名为`child_folder`的子文件夹。
相关问题
删除文件夹 新建文件夹 Python
以下是删除文件夹的两种方法的示例代码:
1. 使用os模块的rmdir()函数删除空文件夹:
```python
import os
os.rmdir("文件夹路径")
```
2. 使用shutil模块的rmtree()函数删除非空文件夹:
```python
import shutil
shutil.rmtree("文件夹路径")
```
请注意,以上代码中的"文件夹路径"需要替换为你要删除的文件夹的实际路径。
查找工作目录下所有Python文件(.py文件),然后将所有Python文件复制到新建文件夹python_code下,最后压缩该文件夹,压缩后的文件命名为python_code.zip。
可以使用以下Python代码实现:
```python
import os
import shutil
import zipfile
# 获取当前工作目录
current_dir = os.getcwd()
# 新建文件夹python_code
new_dir = os.path.join(current_dir, 'python_code')
if not os.path.exists(new_dir):
os.mkdir(new_dir)
# 查找工作目录下所有Python文件(.py文件)
python_files = [f for f in os.listdir(current_dir) if f.endswith('.py')]
# 将所有Python文件复制到新建文件夹python_code下
for file in python_files:
shutil.copy(file, new_dir)
# 压缩该文件夹
zip_file = zipfile.ZipFile('python_code.zip', 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(new_dir):
for file in files:
zip_file.write(os.path.join(root, file))
# 关闭压缩文件
zip_file.close()
```
执行以上代码后,会在当前工作目录下生成python_code.zip文件,其中包含所有Python文件。