2017-06-19 31 views
-2

我想用Python语言编写一个函数,每次创建一个文件夹给定的条件为真多个文件夹。我不知道这个条件会被满足多少次。它会像创建使用循环在python

step_1状况的真实创建文件夹1 step_2状况的真实创建文件夹2 ... step_n状况的真实创建foldern

+1

您可以使用os.makedirs创建新的文件夹(和os.path.exists来检查文件夹是否存在) - 如果这就是你要求的。 – dram

+0

不,我要求的是如何在每次条件为真时自动增加计数器而无需使用for循环,因为我不知道条件将满足多少次。 – ufdul

+1

while your condition is True,keep on looping – dram

回答

1

os.mkdiros.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 
+0

问题是我不知道n(条件是多少次) – ufdul

+0

那么它将有助于了解您的标准是什么。如果你可以将它编码为一个生成器函数,你可以在for循环中使用它,并且完全跳过'if makeadir()'。 – Baldrickk

+0

@ufdul编辑如何? – Baldrickk

0

最简单的方法是使用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 
0
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