2013-07-02 87 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') 你准备好了!