2017-06-19 58 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