Bra*_*eis 467 python directory subdirectory
有没有办法在Python中返回当前目录中所有子目录的列表?
我知道你可以用文件做到这一点,但我需要获取目录列表.
Bla*_*rad 536
你的意思是直接子目录,还是树下的每个目录?
无论哪种方式,您可以使用os.walk这样做:
os.walk(directory)
Run Code Online (Sandbox Code Playgroud)
将为每个子目录生成一个元组.3元组中的第一个条目是目录名称,所以
[x[0] for x in os.walk(directory)]
Run Code Online (Sandbox Code Playgroud)
应该递归地给你所有的子目录.
请注意,元组中的第二个条目是第一个位置中条目的子目录列表,因此您可以使用它,但它不太可能为您节省太多.
但是,您可以使用它只是为了给您直接的子目录:
next(os.walk('.'))[1]
Run Code Online (Sandbox Code Playgroud)
或者查看已发布的其他解决方案,使用os.listdir和os.path.isdir,包括" 如何获取Python中所有直接子目录 "中的那些解决方案.
gah*_*ooa 150
import os
d = '.'
[os.path.join(d, o) for o in os.listdir(d)
if os.path.isdir(os.path.join(d,o))]
Run Code Online (Sandbox Code Playgroud)
小智 125
你可以使用 glob.glob
from glob import glob
glob("/path/to/directory/*/")
Run Code Online (Sandbox Code Playgroud)
不要忘了结尾/之后*.
use*_*036 72
比上面更好,因为你不需要几个os.path.join(),你将直接获得完整的路径(如果你愿意),你可以在Python 3.5+中执行此操作
subfolders = [f.path for f in os.scandir(folder) if f.is_dir() ]
Run Code Online (Sandbox Code Playgroud)
这将给出子目录的完整路径.如果您只想使用子目录的名称f.name而不是f.path
https://docs.python.org/3/library/os.html#os.scandir
Eli*_*sky 35
如果您需要一个可以找到子目录中所有子目录的递归解决方案,请使用之前建议的walk.
如果您只需要当前目录的子目录,请os.listdir与之结合使用os.path.isdir
sve*_*ten 27
我更喜欢使用过滤器(https://docs.python.org/2/library/functions.html#filter),但这只是一个品味问题.
d='.'
filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d))
Run Code Online (Sandbox Code Playgroud)
Cha*_*ith 23
使用python-os-walk实现了这一点.(http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/)
import os
print("root prints out directories only from what you specified")
print("dirs prints out sub-directories from root")
print("files prints out all files from root and directories")
print("*" * 20)
for root, dirs, files in os.walk("/var/log"):
print(root)
print(dirs)
print(files)
Run Code Online (Sandbox Code Playgroud)
小智 20
您可以使用os.listdir(path)获取Python 2.7中的子目录(和文件)列表
import os
os.listdir(path) # list of subdirectories and files
Run Code Online (Sandbox Code Playgroud)
小智 13
print("\nWe are listing out only the directories in current directory -")
directories_in_curdir = filter(os.path.isdir, os.listdir(os.curdir))
print(directories_in_curdir)
Run Code Online (Sandbox Code Playgroud)
files = filter(os.path.isfile, os.listdir(os.curdir))
print("\nThe following are the list of all files in the current directory -")
print(files)
Run Code Online (Sandbox Code Playgroud)
小智 11
由于我使用Python 3.4和Windows UNC路径偶然发现了这个问题,这里有一个适用于这种环境的变体:
from pathlib import WindowsPath
def SubDirPath (d):
return [f for f in d.iterdir() if f.is_dir()]
subdirs = SubDirPath(WindowsPath(r'\\file01.acme.local\home$'))
print(subdirs)
Run Code Online (Sandbox Code Playgroud)
Pathlib是Python 3.4中的新功能,可以更轻松地处理不同操作系统下的路径:https://docs.python.org/3.4/library/pathlib.html
API*_*API 10
虽然很久以前就回答了这个问题.我想建议使用该pathlib模块,因为这是一种在Windows和Unix OS上运行的强大方法.
因此,要获取特定目录中的所有路径,包括子目录:
from pathlib import Path
paths = list(Path('myhomefolder', 'folder').glob('**/*.txt'))
# all sorts of operations
file = paths[0]
file.name
file.stem
file.parent
file.suffix
Run Code Online (Sandbox Code Playgroud)
等等
joe*_*lom 10
蟒3.4引入的pathlib模块到标准库,它提供了一个面向对象的方法来处理的文件系统的路径:
from pathlib import Path
p = Path('./')
# List comprehension
[f for f in p.iterdir() if f.is_dir()]
# The trailing slash to glob indicated directories
# This will also include the current directory '.'
list(p.glob('**/'))
Run Code Online (Sandbox Code Playgroud)
Pathlib也可以通过PyPi上的pathlib2模块在 Python 2.7 上使用.
谢谢提醒伙计.我遇到了一个软链接(无限递归)作为dirs返回的问题.软链接?我们不希望没有stinkin'软链接!所以...
这只是dirs,而不是softlinks:
>>> import os
>>> inf = os.walk('.')
>>> [x[0] for x in inf]
['.', './iamadir']
Run Code Online (Sandbox Code Playgroud)
我就是这样做的。
import os
for x in os.listdir(os.getcwd()):
if os.path.isdir(x):
print(x)
Run Code Online (Sandbox Code Playgroud)
最简单的方法:
from pathlib import Path
from glob import glob
current_dir = Path.cwd()
all_sub_dir_paths = glob(str(current_dir) + '/*/') # returns list of sub directory paths
all_sub_dir_names = [Path(sub_dir).name for sub_dir in all_sub_dir_paths]
Run Code Online (Sandbox Code Playgroud)
在Eli Bendersky的解决方案的基础上,使用以下示例:
import os
test_directory = <your_directory>
for child in os.listdir(test_directory):
test_path = os.path.join(test_directory, child)
if os.path.isdir(test_path):
print test_path
# Do stuff to the directory "test_path"
Run Code Online (Sandbox Code Playgroud)
<your_directory>您要遍历的目录的路径在哪里.
以下是基于@Blair Conrad示例的几个简单函数 -
import os
def get_subdirs(dir):
"Get a list of immediate subdirectories"
return next(os.walk(dir))[1]
def get_subfiles(dir):
"Get a list of immediate subfiles"
return next(os.walk(dir))[2]
Run Code Online (Sandbox Code Playgroud)
复制粘贴友好ipython:
import os
d='.'
folders = list(filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d)))
Run Code Online (Sandbox Code Playgroud)
来自的输出print(folders):
['folderA', 'folderB']
Run Code Online (Sandbox Code Playgroud)
有了完整路径和占路为.,..,\\,..\\..\\subfolder,等:
import os, pprint
pprint.pprint([os.path.join(os.path.abspath(path), x[0]) \
for x in os.walk(os.path.abspath(path))])
Run Code Online (Sandbox Code Playgroud)
这个答案似乎并不存在。
directories = [ x for x in os.listdir('.') if os.path.isdir(x) ]
Run Code Online (Sandbox Code Playgroud)
我最近有一个类似的问题,我发现 python 3.6 的最佳答案(如用户 havlock 添加的)是使用os.scandir. 由于似乎没有使用它的解决方案,因此我将添加自己的解决方案。首先,非递归解决方案,仅列出根目录正下方的子目录。
def get_dirlist(rootdir):
dirlist = []
with os.scandir(rootdir) as rit:
for entry in rit:
if not entry.name.startswith('.') and entry.is_dir():
dirlist.append(entry.path)
dirlist.sort() # Optional, in case you want sorted directory names
return dirlist
Run Code Online (Sandbox Code Playgroud)
递归版本如下所示:
def get_dirlist(rootdir):
dirlist = []
with os.scandir(rootdir) as rit:
for entry in rit:
if not entry.name.startswith('.') and entry.is_dir():
dirlist.append(entry.path)
dirlist += get_dirlist(entry.path)
dirlist.sort() # Optional, in case you want sorted directory names
return dirlist
Run Code Online (Sandbox Code Playgroud)
请记住,它entry.path使用子目录的绝对路径。如果您只需要文件夹名称,entry.name则可以使用。有关该对象的其他详细信息,请参阅os.DirEntryentry。
使用操作系统步行
sub_folders = []
for dir, sub_dirs, files in os.walk(test_folder):
sub_folders.extend(sub_dirs)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
624886 次 |
| 最近记录: |