简体   繁体   English

目录中的 Python 文件夹名称

[英]Python folder names in the directory

how can i get the folder names existing in a directory using Python ?如何使用 Python 获取目录中存在的文件夹名称?

I want to save all the subfolders into a list to work with the names after that but i dont know how to read the subfolder names ?我想将所有子文件夹保存到一个列表中以处理之后的名称,但我不知道如何读取子文件夹名称?

Thanks for you help谢谢你的帮助

You can use os.walk()您可以使用os.walk()

# !/usr/bin/python

import os

directory_list = list()
for root, dirs, files in os.walk("/path/to/your/dir", topdown=False):
    for name in dirs:
        directory_list.append(os.path.join(root, name))

print directory_list

EDIT编辑

If you only want the first level and not actually "walk" through the subdirectories, it is even less code:如果您只想要第一级而不是真正“遍历”子目录,则代码更少:

import os

root, dirs, files = os.walk("/path/to/your/dir").next()
print dirs

This is not really what os.walk is made for.这并不是os.walk真正用途。 If you really only want one level of subdirectories, you can also use os.listdir() like Yannik Ammann suggested:如果你真的只想要一级子目录,你也可以像 Yannik Ammann 建议的那样使用os.listdir()

root='/path/to/my/dir'
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
print dirlist

Starting with Python 3.4, you can also use the new pathlib module:从 Python 3.4 开始,您还可以使用新的pathlib模块:

from pathlib import Path

p = Path('some/folder')
subdirectories = [x for x in p.iterdir() if x.is_dir()]

print(subdirectories)

You should import os first.您应该先导入 os。

import os
files=[]
files = [f for f in sorted(os.listdir(FileDirectoryPath))]

This would give you list with all files in the FileDirectoryPath sorted .这将为您提供在 FileDirectoryPath 中排序的所有文件的列表

You can use os.listdir() here a link to the docs您可以在此处使用os.listdir()链接到文档

Warning returns files and directories警告返回文件和目录

example:例子:

import os

path = 'pyth/to/dir/'
dir_list = os.listdir(path)

update: you need to check if the returned names are directories or files更新:您需要检查返回的名称是目录还是文件

import os

path = 'pyth/to/dir/'
# list of all content in a directory, filtered so only directories are returned
dir_list = [directory for directory in os.listdir(path) if os.path.isdir(path+directory)]

I use os.listdir我使用os.listdir

Get all folder names of a directory获取目录的所有文件夹名称

folder_names = []
for entry_name in os.listdir(MYDIR):
    entry_path = os.path.join(MYDIR, entry_name)
    if os.path.isdir(entry_path):
        folder_names.append(entry_name)

Get all folder paths of a directory获取目录的所有文件夹路径

folder_paths = []
for entry_name in os.listdir(MYDIR):
    entry_path = os.path.join(MYDIR, entry_name)
    if os.path.isdir(entry_path):
        folder_paths.append(entry_path)

Get all file names of a directory获取目录的所有文件名

file_names = []
for file_name in os.listdir(MYDIR):
    file_path = os.path.join(MYDIR, file_name)
    if os.path.isfile(file_path):
        file_names.append(file_name)

Get all file paths of a directory获取目录的所有文件路径

file_paths = []
for file_name in os.listdir(MYDIR):
    file_path = os.path.join(MYDIR, file_name)
    if os.path.isfile(file_path):
        file_paths.append(file_path)

Use os.walk(path)使用os.walk(path)

import os

path = 'C:\\'

for root, directories, files in os.walk(path):
    for directory in directories:
        print os.path.join(root, directory)

For python 3 I'm using this script对于 python 3,我正在使用这个脚本

import os

root='./'
dirlist = [ item for item in os.listdir(root) if os.path.isdir(os.path.join(root, item)) ]
for dir in dirlist:
        print(dir)

Python 3.x: If you want only the directories in a given directory, try: Python 3.x:如果您只想要给定目录中的目录,请尝试:

import os
search_path = '.'   # set your path here.
root, dirs, files = next(os.walk(search_path), ([],[],[]))
print(dirs)

The above example will print out a list of the directories in the current directory like this:上面的例子将打印出当前目录中的目录列表,如下所示:

['dir1', 'dir2', 'dir3']

The output contains only the sub-directory names.输出仅包含子目录名称。
If the directory does not have sub-directories, it will print:如果目录没有子目录,它会打印:

[]

os.walk() is a generator method, so use next() to only call it once. os.walk()是一个生成器方法,所以使用next()只调用一次。 The 3-tuple of empty strings is for the error condition when the directory does not contain any sub-directories because the os.walk() generator returns 3-tuples for each layer in the directory tree.空字符串的三元组用于当目录不包含任何子目录时的错误情况,因为 os.walk() 生成器为目录树中的每一层返回三元组。 Without those, if the directory is empty, next() will raise a StopIteration exception.如果没有这些,如果目录为空,next() 将引发 StopIteration 异常。

For a more compact version:对于更紧凑的版本:

dirs = next(os.walk(search_path), ([],[],[]))[1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python - 仅列出文件夹名称而不是完整目录 - Python - Only listing folder names and not full directory 如何从目录中的文件夹名称中提取后缀字符串? (蟒蛇) - How to Extract A String of the Suffix from Folder Names in a Directory? (Python) 如何从基于 python 文件夹名称列表的目录中获取 select 文件夹? - How to select folders from a directory based on a python list of the folder names? 从目录添加多个文件夹名称到OptionMenu Python - Adding Multiple Folder Names From Directory To OptionMenu Python Python - 将根目录名称与所有子文件夹名称连接起来 - Python - concatenate root directory name with all sub-folder names 如何读取目录中的所有文件夹名称并将文件夹名称写入 CSV python 中的 header? - how to read all folder Names in directory and write folder names as header in CSV python? 顺序目录名称Python 3 - Sequential Directory Names Python 3 python:从不同文件目录导入模块,文件夹名称带有空格 - python: import module from different file directory, with folder names having spaces Python比较XML.Etree以及目录列表中的文件和文件夹名称的差异 - Python compare differences in XML.Etree and file and folder names in directory listings 提取目录中的文件夹名称列表后,如何使用 Python 将它们重命名为另一种格式? - After extracting the list of folder names in a directory, how do I rename them in another format using Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM