我试图写一个简单的Python脚本,将复制索引。在所有子目录(少数例外)中将TPL转换为index.html。
我在获取子目录列表时陷入了困境。
我试图写一个简单的Python脚本,将复制索引。在所有子目录(少数例外)中将TPL转换为index.html。
我在获取子目录列表时陷入了困境。
当前回答
选中“获取当前目录中所有子目录的列表”。
下面是Python 3的版本:
import os
dir_list = next(os.walk('.'))[1]
print(dir_list)
其他回答
我必须提到path.py库,我经常使用它。
获取直接子目录变得如此简单:
my_dir.dirs ()
完整的工作示例是:
from path import Path
my_directory = Path("path/to/my/directory")
subdirs = my_directory.dirs()
注意:my_directory仍然可以作为字符串操作,因为Path是string的子类,但提供了一堆有用的方法来操作路径
我只是写了一些代码来移动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))
它不是特别优雅,但确实有用。
import pathlib
def list_dir(dir):
path = pathlib.Path(dir)
dir = []
try:
for item in path.iterdir():
if item.is_dir():
dir.append(item)
return dir
except FileNotFoundError:
print('Invalid directory')
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)
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']