2013-07-02 88 views
0

我有一個充滿子目錄的目錄。遍歷目錄列表以創建子目錄

我想要做的是編寫一個Python腳本,通過這些 子目錄中的每一個循環,併爲每個子目錄創建一個附加的子目錄並使用三個文件填充 。

例如:

directories = ['apple', 'orange', 'banana'] 

for fruit in directories: 

# 1) create subdirectory called "files" 
# 2) Populate "files" with file1, file2, file3 

我所熟悉的在終端的命令行(蘋果機) 創建的目錄和文件,但我不知道如何從Python中調用這些命令。

我非常感謝這些命令的外觀以及如何使用它們。

回答

1

您可以使用內建函數os.path.walk(通過目錄樹行走)和os.mkdir(實際上是創建目錄)達到你想要什麼。

+0

我一直在閱讀操作系統庫,試圖查看它在創建文件的位置,類似於使用mkdir創建目錄的方式,但我找不到任何東西。你有什麼建議嗎 – user2521067

+0

你想創建一個新的空文件並寫信給它,或者只是從別的地方複製一個?如果要寫入新文件,請使用內建[打開](http://docs.python.org/2/library/functions.html#open)函數並寫入文件。如果您想複製現有文件,請使用[shutil.copy](http://docs.python.org/2/library/shutil.html)。 – bogatron

0

Python os模塊擁有創建目錄所需的全部功能,特別是os.mkdir()

你不會在這些文件中說你想要什麼。如果您需要另一個(「模板」)文件的副本,請使用shutil.copy()如果您想通過腳本創建一個新文件和wrrite,內置的open()就足夠了。

下面是一個例子(注意,假設「果」目錄在當前目錄該子目錄「文件」並不存在已經存在):

import os 
import shutil 

directories = ['apple', 'orange', 'banana'] 

for fruit in directories: 

    os.mkdir("%s/files" % fruit) 

    with open("%s/files/like" % fruit, "w") as fp: 
     fp.write("I like %ss" % fruit) 
    fp.close() 

    with open("%s/files/hate" % fruit, "w") as fp: 
     fp.write("I hate %ss" % fruit) 
    fp.close() 

    with open("%s/files/dont_care_about" % fruit, "w") as fp: 
     fp.write("I don't care about %ss" % fruit) 
    fp.close() 
0

使用Python import osos.system('command_to_run_in_shell') 你準備好了!