可以使用os模块来判断文件夹是否存在,并使用for循环来创建文件夹。

代码如下:

import os

folders = ["folder1", "folder2", "folder3", "folder4"]

for folder in folders:
    if not os.path.exists(folder):
        os.mkdir(folder)
        print(f"Folder '{folder}' created.")
    else:
        print(f"Folder '{folder}' already exists, skipping.")

解释:

  1. 首先定义了一个列表folders,包含了需要创建的文件夹的名称。

  2. 然后使用for循环遍历列表中的每个文件夹名称。

  3. 在循环中,使用os.path.exists()函数判断文件夹是否存在。如果不存在,就使用os.mkdir()函数创建文件夹,并输出提示信息。

  4. 如果文件夹已经存在,就直接输出提示信息,跳过创建过程

python 循环创建4个文件夹 如果存在则跳过

原文地址: https://www.cveoy.top/t/topic/fJUc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录