Hướng dẫn how do i get a list of directories in a directory in python? - làm cách nào để có danh sách thư mục trong thư mục trong python?

Đẹp hơn nhiều so với ở trên, vì bạn không cần một số os.path.join [] và bạn sẽ nhận được đường dẫn đầy đủ [nếu bạn muốn], bạn có thể làm điều này trong Python 3.5 trở lên.Python 3.5 and above.

subfolders = [ f.path for f in os.scandir[folder] if f.is_dir[] ]

Điều này sẽ cung cấp cho con đường hoàn chỉnh đến thư mục con. Nếu bạn chỉ muốn tên của thư mục con f.name thay vì f.path

//docs.python.org/3/library/os.html#os.scandir

Hơi OT: Trong trường hợp bạn cần tất cả các thư mục con đệ quy và/hoặc tất cả các tệp một cách đệ quy, hãy xem chức năng này, nhanh hơn os.walk & glob và sẽ trả về danh sách tất cả các thư mục con cũng như tất cả các tệp bên trong đó [phụ] Các thư mục con: //stackoverflow.com/a/59803793/2441026all subfolder recursively and/or all files recursively, have a look at this function, that is faster than os.walk & glob and will return a list of all subfolders as well as all files inside those [sub-]subfolders: //stackoverflow.com/a/59803793/2441026

Trong trường hợp bạn chỉ muốn tất cả các thư mục con đệ quy:all subfolders recursively:

def fast_scandir[dirname]:
    subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
    for dirname in list[subfolders]:
        subfolders.extend[fast_scandir[dirname]]
    return subfolders

Trả về một danh sách tất cả các thư mục con với đường dẫn đầy đủ của chúng. Điều này một lần nữa nhanh hơn os.walk và nhanh hơn rất nhiều so với glob.

Phân tích tất cả các chức năng

TL; DR: - Nếu bạn muốn nhận tất cả các thư mục con ngay lập tức cho một thư mục sử dụng ____10. - Nếu bạn muốn có được tất cả các thư mục con, thậm chí là lồng nhau, hãy sử dụng os.walk hoặc - nhanh hơn một chút - hàm

def fast_scandir[dirname]:
    subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
    for dirname in list[subfolders]:
        subfolders.extend[fast_scandir[dirname]]
    return subfolders
2 ở trên. - Không bao giờ sử dụng os.walk chỉ cho các thư mục con cấp cao nhất, vì nó có thể chậm hơn hàng trăm [!] Của thời gian so với
def fast_scandir[dirname]:
    subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
    for dirname in list[subfolders]:
        subfolders.extend[fast_scandir[dirname]]
    return subfolders
0.
- If you want to get all immediate subdirectories for a folder use
def fast_scandir[dirname]:
    subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
    for dirname in list[subfolders]:
        subfolders.extend[fast_scandir[dirname]]
    return subfolders
0.
- If you want to get all subdirectories, even nested ones, use os.walk or - slightly faster - the
def fast_scandir[dirname]:
    subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
    for dirname in list[subfolders]:
        subfolders.extend[fast_scandir[dirname]]
    return subfolders
2 function above.
- Never use os.walk for only top-level subdirectories, as it can be hundreds[!] of times slower than
def fast_scandir[dirname]:
    subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
    for dirname in list[subfolders]:
        subfolders.extend[fast_scandir[dirname]]
    return subfolders
0.

  • Nếu bạn chạy mã bên dưới, hãy đảm bảo chạy nó một lần để HĐH của bạn sẽ truy cập thư mục, loại bỏ kết quả và chạy thử nghiệm, nếu không, kết quả sẽ được vặn vẹo.
  • Bạn có thể muốn trộn các cuộc gọi chức năng, nhưng tôi đã thử nghiệm nó và nó không thực sự quan trọng.
  • Tất cả các ví dụ sẽ đưa ra đường dẫn đầy đủ đến thư mục. Ví dụ Pathlib dưới dạng đối tượng đường dẫn [Windows].
  • Yếu tố đầu tiên của os.walk sẽ là thư mục cơ sở. Vì vậy, bạn sẽ không chỉ nhận được các thư mục con. Bạn có thể sử dụng
    def fast_scandir[dirname]:
        subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
        for dirname in list[subfolders]:
            subfolders.extend[fast_scandir[dirname]]
        return subfolders
    
    6 để loại bỏ nó.
  • Không có kết quả nào sẽ sử dụng phân loại tự nhiên. Điều này có nghĩa là kết quả sẽ được sắp xếp như thế này: 1, 10, 2. Để có được sự phân loại tự nhiên [1, 2, 10], xin vui lòng xem //stackoverflow.com/a/48030307/2441026. This means results will be sorted like this: 1, 10, 2. To get natural sorting [1, 2, 10], please have a look at //stackoverflow.com/a/48030307/2441026

Kết quả::

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439

Được thử nghiệm với W7X64, Python 3.8.1.

# -*- coding: utf-8 -*-
# Python 3


import time
import os
from glob import glob
from pathlib import Path


directory = r""
RUNS = 1


def run_os_walk[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        fu = [x[0] for x in os.walk[directory]]
    print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_glob[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        fu = glob[directory + "/*/"]
    print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_pathlib_iterdir[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        dirname = Path[directory]
        fu = [f for f in dirname.iterdir[] if f.is_dir[]]
    print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_os_listdir[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        dirname = Path[directory]
        fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]]
    print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_os_scandir[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        fu = [f.path for f in os.scandir[directory] if f.is_dir[]]
    print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"]


if __name__ == '__main__':
    run_os_scandir[]
    run_os_walk[]
    run_glob[]
    run_pathlib_iterdir[]
    run_os_listdir[]

Forpath inglob.glob [f '{rootDir}/*/']:

& nbsp; Python 3.5 Hỗ trợ mở rộng cho các quả cầu đệ quy bằng cách sử dụng
# -*- coding: utf-8 -*-
# Python 3


import time
import os
from glob import glob
from pathlib import Path


directory = r""
RUNS = 1


def run_os_walk[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        fu = [x[0] for x in os.walk[directory]]
    print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_glob[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        fu = glob[directory + "/*/"]
    print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_pathlib_iterdir[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        dirname = Path[directory]
        fu = [f for f in dirname.iterdir[] if f.is_dir[]]
    print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_os_listdir[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        dirname = Path[directory]
        fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]]
    print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_os_scandir[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        fu = [f.path for f in os.scandir[directory] if f.is_dir[]]
    print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"]


if __name__ == '__main__':
    run_os_scandir[]
    run_os_walk[]
    run_glob[]
    run_pathlib_iterdir[]
    run_os_listdir[]
7 để tìm kiếm các thư mục con và liên kết tượng trưng đến các thư mục.

forpath inglob.glob [f '{rootDir}/*/*/' ', recursive = true]:

Nhập khẩuos

rootdir='path/to/dir'='path/to/dir'

forfileinos.listdir[rootdir]:file inos.listdir[rootdir]:

    d=os.path.join[rootdir,file]d=os.path.join[rootdir,file]

    ifos.path.isdir[d]:ifos.path.isdir[d]:

        print[d]print[d]

Tải xuống mã

& nbsp; & nbsp; & nbsp; & nbsp; forit inos.scandir [rootDir]:
You can easily extend the solution to search within subdirectories as well, as shown below:

Nhập khẩuos

deflistdirs[rootdir]:listdirs[rootdir]:

    forfileinos.listdir[rootdir]:forfileinos.listdir[rootdir]:

        d=os.path.join[rootdir,file]d=os.path.join[rootdir, file]

        ifos.path.isdir[d]:if os.path.isdir[d]:

            print[d]print[d]

            listdirs[d]listdirs[d]

rootdir='path/to/dir' ='path/to/dir'

listdirs[rootdir][rootdir]

Tải xuống mã

2. Sử dụng hàm
os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
0

Với Python 3.5, bạn có thể sử dụng chức năng

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
0, cung cấp hiệu suất tốt hơn đáng kể so với
def fast_scandir[dirname]:
    subfolders= [f.path for f in os.scandir[dirname] if f.is_dir[]]
    for dirname in list[subfolders]:
        subfolders.extend[fast_scandir[dirname]]
    return subfolders
7. Nó trả về các mục nhập thư mục cùng với thông tin thuộc tính tệp. Để lọc các mục được trả về để loại trừ các tệp, hãy gọi hàm
os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
3, trả về
os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
4 nếu mục nhập hiện tại là thư mục hoặc liên kết tượng trưng chỉ vào thư mục.

Nhập khẩuos

rootdir='path/to/dir'='path/to/dir'

Forit inos.Scandir [rootDir]:it inos.scandir[rootdir]:

    ifit.is_dir[]:ifit.is_dir[]:

        print[it.path]print[it.path]

Tải xuống mã

& nbsp; Bạn có thể dễ dàng làm cho mã trên đệ quy để cho phép tìm kiếm trong các thư mục con:
You can easily make the above code recursive to enable search within subdirectories:

Nhập khẩuos

deflistdirs[rootdir]:listdirs[rootdir]:

Forit inos.Scandir [rootDir]:forit inos.scandir[rootdir]:

        ifit.is_dir[]:ifit.is_dir[]:

            print[it.path]print[it.path]

            listdirs[it]listdirs[it]

rootdir='path/to/dir'='path/to/dir'

listdirs[rootdir][rootdir]

Tải xuống mã

& nbsp; Bạn có thể dễ dàng làm cho mã trên đệ quy để cho phép tìm kiếm trong các thư mục con:

& nbsp; & nbsp; & nbsp; & nbsp; forit inos.scandir [rootDir]:

3. Sử dụng mô -đun

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
5pathlib importPath

rootdir='path/to/dir'='path/to/dir'

Bạn cũng có thể sử dụng mô -đun

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
5 với Python 3.4 để liệt kê tất cả các thư mục con trong một thư mục. Ý tưởng là gọi hàm
os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
7, mang lại các đối tượng đường dẫn của nội dung thư mục. Bạn có thể lọc các đối tượng được trả về cho các thư mục hoặc liên kết tượng trưng chỉ vào thư mục, sử dụng hàm ____28.path in Path[rootdir].iterdir[]:

    ifpath.is_dir[]:if path.is_dir[]:

        print[path]print[path]

Tải xuống mã

& nbsp; Bạn có thể dễ dàng làm cho mã trên đệ quy để cho phép tìm kiếm trong các thư mục con:
Here’s the recursive version, which also searches within the subdirectories:

3. Sử dụng mô -đun

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
5pathlib importPath

deflistdirs[rootdir]: listdirs[rootdir]:

Bạn cũng có thể sử dụng mô -đun

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
5 với Python 3.4 để liệt kê tất cả các thư mục con trong một thư mục. Ý tưởng là gọi hàm
os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
7, mang lại các đối tượng đường dẫn của nội dung thư mục. Bạn có thể lọc các đối tượng được trả về cho các thư mục hoặc liên kết tượng trưng chỉ vào thư mục, sử dụng hàm ____28.forpath in Path[rootdir].iterdir[]:

        ifpath.is_dir[]:ifpath.is_dir[]:

            print[path]print[path]

            listdirs[path]listdirs[path]

rootdir='path/to/dir'='path/to/dir'

listdirs[rootdir][rootdir]

Tải xuống mã

& nbsp; Bạn có thể dễ dàng làm cho mã trên đệ quy để cho phép tìm kiếm trong các thư mục con:

& nbsp; & nbsp; & nbsp; & nbsp; forit inos.scandir [rootDir]:

Nhập khẩuos

rootdir='path/to/dir'='path/to/dir'

Forit inos.Scandir [rootDir]: rootdir,dirs,files in os.walk[rootdir]:

Tải xuống mãforsubdir indirs:

        print[os.path.join[rootdir,subdir]]print[os.path.join[rootdir,subdir]]

Tải xuống mã

& nbsp; Bạn có thể dễ dàng làm cho mã trên đệ quy để cho phép tìm kiếm trong các thư mục con:

& nbsp; & nbsp; & nbsp; & nbsp; forit inos.scandir [rootDir]:

3. Sử dụng mô -đun

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
5glob

rootdir='path/to/dir'='path/to/dir'

Bạn cũng có thể sử dụng mô -đun

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
5 với Python 3.4 để liệt kê tất cả các thư mục con trong một thư mục. Ý tưởng là gọi hàm
os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
7, mang lại các đối tượng đường dẫn của nội dung thư mục. Bạn có thể lọc các đối tượng được trả về cho các thư mục hoặc liên kết tượng trưng chỉ vào thư mục, sử dụng hàm ____28.path inglob.glob[f'{rootdir}/*/']:

    print[path]print[path]

Tải xuống mã

& nbsp; Bạn có thể dễ dàng làm cho mã trên đệ quy để cho phép tìm kiếm trong các thư mục con:
Python 3.5 extended support for recursive globs using

# -*- coding: utf-8 -*-
# Python 3


import time
import os
from glob import glob
from pathlib import Path


directory = r""
RUNS = 1


def run_os_walk[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        fu = [x[0] for x in os.walk[directory]]
    print[f"os.walk\t\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_glob[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        fu = glob[directory + "/*/"]
    print[f"glob.glob\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_pathlib_iterdir[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        dirname = Path[directory]
        fu = [f for f in dirname.iterdir[] if f.is_dir[]]
    print[f"pathlib.iterdir\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_os_listdir[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        dirname = Path[directory]
        fu = [os.path.join[directory, o] for o in os.listdir[directory] if os.path.isdir[os.path.join[directory, o]]]
    print[f"os.listdir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len[fu]}"]


def run_os_scandir[]:
    a = time.time_ns[]
    for i in range[RUNS]:
        fu = [f.path for f in os.scandir[directory] if f.is_dir[]]
    print[f"os.scandir\t\ttook {[time.time_ns[] - a] / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len[fu]}"]


if __name__ == '__main__':
    run_os_scandir[]
    run_os_walk[]
    run_glob[]
    run_pathlib_iterdir[]
    run_os_listdir[]
7 to search subdirectories and symbolic links to directories.

3. Sử dụng mô -đun

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
5glob

rootdir='path/to/dir'='path/to/dir'

Bạn cũng có thể sử dụng mô -đun

os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
5 với Python 3.4 để liệt kê tất cả các thư mục con trong một thư mục. Ý tưởng là gọi hàm
os.scandir      took   1 ms. Found dirs: 439
os.walk         took 463 ms. Found dirs: 441 -> it found the nested one + base folder.
glob.glob       took  20 ms. Found dirs: 439
pathlib.iterdir took  18 ms. Found dirs: 439
os.listdir      took  18 ms. Found dirs: 439
7, mang lại các đối tượng đường dẫn của nội dung thư mục. Bạn có thể lọc các đối tượng được trả về cho các thư mục hoặc liên kết tượng trưng chỉ vào thư mục, sử dụng hàm ____28.path inglob.glob[f'{rootdir}/*/**/', recursive=True]:

    print[path]print[path]

Tải xuống mã

& nbsp; Bạn có thể dễ dàng làm cho mã trên đệ quy để cho phép tìm kiếm trong các thư mục con:

Làm thế nào tôi có thể nhận được một danh sách các tệp trong một thư mục?

Xem các ví dụ sau:..
Để liệt kê tất cả các tệp trong thư mục hiện tại, hãy nhập các loại sau: LS -a này liệt kê tất cả các tệp, bao gồm.DOT [.] ....
Để hiển thị thông tin chi tiết, hãy nhập các loại sau: LS -L Chap1 .Profile.....
Để hiển thị thông tin chi tiết về một thư mục, hãy nhập như sau: ls -d -l ..

Làm thế nào tôi có thể nhận được một danh sách tất cả các thư mục con và tệp có trong một thư mục bằng PHP?

PHP sử dụng scandir [] để tìm các thư mục trong thư mục hàm scandir là một hàm sẵn có trả về một loạt các tệp và thư mục của một thư mục cụ thể.Nó liệt kê các tệp và thư mục có bên trong đường dẫn được chỉ định bởi người dùng.scandir[] to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.

Chủ Đề