我想用Python语言编写一个函数,每次创建一个文件夹给定的条件为真多个文件夹。我不知道这个条件会被满足多少次。它会像创建使用循环在python
step_1状况的真实创建文件夹1 step_2状况的真实创建文件夹2 ... step_n状况的真实创建foldern
我想用Python语言编写一个函数,每次创建一个文件夹给定的条件为真多个文件夹。我不知道这个条件会被满足多少次。它会像创建使用循环在python
step_1状况的真实创建文件夹1 step_2状况的真实创建文件夹2 ... step_n状况的真实创建foldern
与os.mkdir
或os.mkdirs
https://docs.python.org/2/library/os.html
环路
os.mkdir(path[, mode])
使用数字模式模式创建名为path的目录。默认模式是0777(八进制)。如果该目录已经存在,则引发OSError为 。
在某些系统上,模式被忽略。在使用它的地方,当前的umask值首先被屏蔽掉。如果除了最后9位(即 模式的八进制表示的最后3位数)被设置,它们的含义是平台相关的。在某些平台上,它们被忽略了 ,你应该明确调用chmod()来设置它们。
也可以创建临时目录;请参阅tempfile模块的tempfile.mkdtemp()函数。
可用性:Unix,Windows。
os.makedirs(path[, mode])
递归目录创建功能。像mkdir()一样,但是使所有需要包含叶目录的中级目录。 如果叶目录已经存在或者无法创建 ,则引发错误异常。默认模式是0777(八进制)。
模式参数被传递给MKDIR();请参阅mkdir()说明以了解它的解释。
所以像:
import os
for i in range(n):
# makeadir() evaluates your condition
if makeadir(i):
path = 'folder {}'.format(i)
if not os.path.exists(path):
os.mkdir(path)
编辑:如果你有一个条件:
import os
i = 1
while eval_condition():
path = 'folder {}'.format(i)
if not os.path.exists(path):
os.mkdir(path)
i += 1
最简单的方法是使用while循环使用一个计数器来怎么算很多次它都被圈起来了。
import os
counter=1
while statement:
os.mkdir('folder{}'.format(str(counter)))
counter += 1
# give a new value to your statement to keep creating or stop creating directories
statement = true
import os
condition_success = 0 # set initial 0
while True:
condition_success += 1 # get counter for condition to increment if condition is true:
# By default this will create folder within same directory
os.makedirs("folder"+str(condition_success)) # creates folder1 if condition_success is 1
创建目录地方设置路径,它
path = "/path/" os.makedirs(path + "folder"+str(condition_success))
,或者你可以直接将其创建为
os.makedirs("/path/folder"+str(condition_success))
condition_success = 0 usr_input = int(input("Enter number to create number of folder/execute condition: ")) # get number from user input while True: condition_success += 1 # get counter for condition to increment if condition is true: # By default this will create folder within same directory os.makedirs("folder"+str(condition_success)) # creates folder1 if condition_success is 1 if condition_success >= usr_input: break
您可以使用os.makedirs创建新的文件夹(和os.path.exists来检查文件夹是否存在) - 如果这就是你要求的。 – dram
不,我要求的是如何在每次条件为真时自动增加计数器而无需使用for循环,因为我不知道条件将满足多少次。 – ufdul
while your condition is True,keep on looping – dram