我试图写一个简单的Python脚本,将复制索引。在所有子目录(少数例外)中将TPL转换为index.html。
我在获取子目录列表时陷入了困境。
我试图写一个简单的Python脚本,将复制索引。在所有子目录(少数例外)中将TPL转换为index.html。
我在获取子目录列表时陷入了困境。
当前回答
import glob
import os
def child_dirs(path):
cd = os.getcwd() # save the current working directory
os.chdir(path) # change directory
dirs = glob.glob("*/") # get all the subdirectories
os.chdir(cd) # change directory to the script original location
return dirs
child_dirs函数的作用是:获取一个目录的路径,并返回其中直接子目录的列表。
dir
|
-- dir_1
-- dir_2
child_dirs('dir') -> ['dir_1', 'dir_2']
其他回答
这个方法很好地一次性完成了这一切。
from glob import glob
subd = [s.rstrip("/") for s in glob(parent_dir+"*/")]
import os
def get_immediate_subdirectories(a_dir):
return [name for name in os.listdir(a_dir)
if os.path.isdir(os.path.join(a_dir, name))]
使用Twisted的FilePath模块:
from twisted.python.filepath import FilePath
def subdirs(pathObj):
for subpath in pathObj.walk():
if subpath.isdir():
yield subpath
if __name__ == '__main__':
for subdir in subdirs(FilePath(".")):
print "Subdirectory:", subdir
由于一些评论者问使用Twisted的库有什么好处,我将在这里稍微超出最初的问题。
分支中有一些改进的文档解释了FilePath的优点;你可能会想读一下。
More specifically in this example: unlike the standard library version, this function can be implemented with no imports. The "subdirs" function is totally generic, in that it operates on nothing but its argument. In order to copy and move the files using the standard library, you need to depend on the "open" builtin, "listdir", perhaps "isdir" or "os.walk" or "shutil.copy". Maybe "os.path.join" too. Not to mention the fact that you need a string passed an argument to identify the actual file. Let's take a look at the full implementation which will copy each directory's "index.tpl" to "index.html":
def copyTemplates(topdir):
for subdir in subdirs(topdir):
tpl = subdir.child("index.tpl")
if tpl.exists():
tpl.copyTo(subdir.child("index.html"))
上面的“subdirs”函数可以作用于任何类filepath对象。这意味着,其中包括ZipPath对象。不幸的是,ZipPath现在是只读的,但是可以扩展到支持写入。
您还可以为测试目的传递自己的对象。为了测试操作系统。在这里建议使用path-using api时,您必须处理导入的名称和隐式依赖项,并通常执行黑魔法以使您的测试正常工作。使用FilePath,你可以这样做:
class MyFakePath:
def child(self, name):
"Return an appropriate child object"
def walk(self):
"Return an iterable of MyFakePath objects"
def exists(self):
"Return true or false, as appropriate to the test"
def isdir(self):
"Return true or false, as appropriate to the test"
...
subdirs(MyFakePath(...))
我只是写了一些代码来移动vmware虚拟机,最终使用os。路径和shutil来完成子目录之间的文件复制。
def copy_client_files (file_src, file_dst):
for file in os.listdir(file_src):
print "Copying file: %s" % file
shutil.copy(os.path.join(file_src, file), os.path.join(file_dst, file))
它不是特别优雅,但确实有用。
为什么没有人提到glob?glob允许您使用unix风格的路径名展开,它是我的go to函数,几乎适用于需要查找多个路径名的所有内容。这很简单:
from glob import glob
paths = glob('*/')
请注意,glob将返回带有最后斜杠的目录(就像unix一样),而大多数基于路径的解决方案将省略最后的斜杠。