我试图写一个简单的Python脚本,将复制索引。在所有子目录(少数例外)中将TPL转换为index.html。
我在获取子目录列表时陷入了困境。
我试图写一个简单的Python脚本,将复制索引。在所有子目录(少数例外)中将TPL转换为index.html。
我在获取子目录列表时陷入了困境。
当前回答
这里有一种方法:
import os
import shutil
def copy_over(path, from_name, to_name):
for path, dirname, fnames in os.walk(path):
for fname in fnames:
if fname == from_name:
shutil.copy(os.path.join(path, from_name), os.path.join(path, to_name))
copy_over('.', 'index.tpl', 'index.html')
其他回答
这里有一种方法:
import os
import shutil
def copy_over(path, from_name, to_name):
for path, dirname, fnames in os.walk(path):
for fname in fnames:
if fname == from_name:
shutil.copy(os.path.join(path, from_name), os.path.join(path, to_name))
copy_over('.', 'index.tpl', 'index.html')
使用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(...))
import os
获取目录下的(全路径)直接子目录:
def SubDirPath (d):
return filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)])
获取最新(latest)子目录:
def LatestDirectory (d):
return max(SubDirPath(d), key=os.path.getmtime)
操作系统。在这种情况下,走路是你的朋友。
直接从文档中:
Walk()通过自顶向下或自底向上遍历目录树来生成目录树中的文件名。对于根在目录顶部的树中的每个目录(包括top本身),它会生成一个3元组(dirpath、dirnames、filename)。
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']