Hướng dẫn how do i count files in a directory and subfolders in python? - làm cách nào để đếm tệp trong thư mục và thư mục con trong python?

Cố gắng tạo một chức năng trả về # của các tệp đã tìm thấy một thư mục và các thư mục con của nó. Chỉ cần trợ giúp để bắt đầu

Đã hỏi ngày 4 tháng 6 năm 2013 lúc 5:22Jun 4, 2013 at 5:22

Lót

import os
cpt = sum[[len[files] for r, d, files in os.walk["G:\CS\PYTHONPROJECTS"]]]

Đã trả lời ngày 4 tháng 6 năm 2013 lúc 6:13Jun 4, 2013 at 6:13

Kiriloffkiriloffkiriloff

25K36 Huy hiệu vàng142 Huy hiệu bạc220 Huy hiệu đồng36 gold badges142 silver badges220 bronze badges

3

Chỉ cần thêm một tuyên bố

def fileCount[folder]:
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir[folder]:
        path = os.path.join[folder, filename]

        if os.path.isfile[path]:
            count += 1
        elif os.path.isfolder[path]:
            count += fileCount[path]

    return count
1 chăm sóc các thư mục:

def fileCount[folder]:
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir[folder]:
        path = os.path.join[folder, filename]

        if os.path.isfile[path]:
            count += 1
        elif os.path.isfolder[path]:
            count += fileCount[path]

    return count

Đã trả lời ngày 4 tháng 6 năm 2013 lúc 5:26Jun 4, 2013 at 5:26

BlenderBlenderBlender

Phù bằng vàng 282K52430 Huy hiệu bạc488 Huy hiệu đồng52 gold badges430 silver badges488 bronze badges

1

  • Dưới đây là một số lớp lót sử dụng pathlib, là một phần của thư viện tiêu chuẩn.
  • Sử dụng
    def fileCount[folder]:
        "count the number of files in a directory"
    
        count = 0
    
        for filename in os.listdir[folder]:
            path = os.path.join[folder, filename]
    
            if os.path.isfile[path]:
                count += 1
            elif os.path.isfolder[path]:
                count += fileCount[path]
    
        return count
    
    2 hoặc
    def fileCount[folder]:
        "count the number of files in a directory"
    
        count = 0
    
        for filename in os.listdir[folder]:
            path = os.path.join[folder, filename]
    
            if os.path.isfile[path]:
                count += 1
            elif os.path.isfolder[path]:
                count += fileCount[path]
    
        return count
    
    3, tạo ra một trình tạo của tất cả các tệp.
    • Giải nén trình tạo bằng
      def fileCount[folder]:
          "count the number of files in a directory"
      
          count = 0
      
          for filename in os.listdir[folder]:
              path = os.path.join[folder, filename]
      
              if os.path.isfile[path]:
                  count += 1
              elif os.path.isfolder[path]:
                  count += fileCount[path]
      
          return count
      
      4 hoặc
      def fileCount[folder]:
          "count the number of files in a directory"
      
          count = 0
      
          for filename in os.listdir[folder]:
              path = os.path.join[folder, filename]
      
              if os.path.isfile[path]:
                  count += 1
              elif os.path.isfolder[path]:
                  count += fileCount[path]
      
          return count
      
      5 và sử dụng
      def fileCount[folder]:
          "count the number of files in a directory"
      
          count = 0
      
          for filename in os.listdir[folder]:
              path = os.path.join[folder, filename]
      
              if os.path.isfile[path]:
                  count += 1
              elif os.path.isfolder[path]:
                  count += fileCount[path]
      
          return count
      
      6 để có được số lượng tệp.
  • Xem cách đếm tổng số tệp trong mỗi thư mục con để lấy tổng số tệp cho mỗi thư mục.
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]

Đã trả lời ngày 30 tháng 8 lúc 14:54Aug 30 at 14:54

Trenton McKinneyTrenton McKinneyTrenton McKinney

49.3K31 Huy hiệu vàng120 Huy hiệu bạc133 Huy hiệu đồng31 gold badges120 silver badges133 bronze badges

Đây là phiên bản của tôi

def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count

def fileCount[folder]:
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir[folder]:
        path = os.path.join[folder, filename]

        if os.path.isfile[path]:
            count += 1
        elif os.path.isfolder[path]:
            count += fileCount[path]

    return count
7

def fileCount[folder]:
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir[folder]:
        path = os.path.join[folder, filename]

        if os.path.isfile[path]:
            count += 1
        elif os.path.isfolder[path]:
            count += fileCount[path]

    return count
8

def fileCount[folder]:
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir[folder]:
        path = os.path.join[folder, filename]

        if os.path.isfile[path]:
            count += 1
        elif os.path.isfolder[path]:
            count += fileCount[path]

    return count
9

Đã trả lời ngày 19 tháng 6 lúc 11:10Jun 19 at 11:10

Làm thế nào để đếm các tệp trong một thư mục với Python?

Làm việc trong Python với các tập tin và thư mục một cách hiệu quả rất quan trọng đặc biệt là khi chúng ta đang nói về hàng ngàn tệp.

Ví dụ: nếu mục tiêu là chỉ cần tính số lượng tệp trong một thư mục, có lẽ bạn nên làm việc trực tiếp với Iterables mà không cần tạo các danh sách sẽ chiếm nhiều bộ nhớ hơn.

Ở đây chúng tôi sẽ cố gắng làm điều này bất cứ khi nào có thể bằng cách áp dụng các chức năng từ các mô-đun tích hợp Python, như

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
0,
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
1,
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
2 và
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
3.

Ngoài ra để chỉ ra cách sử dụng chúng, chúng tôi sẽ so sánh ngắn gọn chúng và xem cái nào có thể được áp dụng để thực hiện số lượng tệp đệ quy.

Chúng tôi sẽ giới thiệu các ví dụ đến một cấu trúc tệp đơn giản như trong hình. Thư mục trực tuyến

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
4, chứa một thư mục con ____ ____25 và ba tệp bao gồm một tệp văn bản, hình ảnh và phím tắt.

Tên của tệp văn bản bắt đầu bằng một dấu chấm [trong Linux, nó sẽ là một tệp ẩn] và chúng ta sẽ thấy rằng nếu chúng ta sử dụng ____ ____ ____21 [Phương pháp 4], nó sẽ không tính nó.

Bên trong thư mục con

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
5, chỉ có một tệp văn bản. Loại tệp không quan trọng ở đây.

Hãy giả sử rằng đường dẫn đến thư mục ____ ____24 [áp dụng định dạng Windows] là:

& nbsp; Hồi ____ ____ 29 và chúng tôi lưu trữ nó trong biến số ____ ____ 30. & nbsp; & nbsp; & nbsp;

Phương pháp 1: Sử dụng Os.ListDir [] và Os.Path.isfile []

Đây là một phương pháp không nhận được.

Mô -đun ____ ____ ____2020 cho phép bạn sử dụng nhiều tính năng của hệ điều hành. Ở đây chúng tôi sử dụng một trong các chức năng của nó,

def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
2 với đối số
def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
0, để có được một danh sách với tên của tất cả các tệp và thư mục con có trong Hồi ____ ____24.

Đối với điều này, bạn cũng có thể sử dụng

def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
5, như tài liệu Python chính thức cho biết, hiệu quả hơn đối với nhiều trường hợp sử dụng phổ biến.

Mô -đun

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
2 thực hiện một số chức năng để thao tác tên đường dẫn và ở đây chúng tôi sử dụng hàm
def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
7 để xác định và chỉ đếm các tệp là tệp.

Hãy cùng xem một số ví dụ:

import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3

Kết quả trong cả hai trường hợp là 3 vì phương pháp này không đệ quy và không tính

def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
8 bên trong thư mục con ____ ____25

Phương pháp 2: Sử dụng Os.Scandir []

Đây là một phương pháp không nhận được.

Hàm

import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
0 của mô -đun
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
0 trả về một trình lặp lại của các đối tượng
import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
2. Mỗi phần tử chứa trong thư mục được chỉ định sẽ được biểu thị bằng một đối tượng
import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
2 ngoài đường dẫn còn chứa các thuộc tính khác của cùng một.

Do đó, tận dụng thông tin này, chúng tôi sẽ biết liệu một cái gì đó có phải là một tệp hay không bằng cách áp dụng

import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
4 của mô -đun
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
0 mà không cần phải sử dụng hàm
def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
7 của mô -đun
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
2.

Phương pháp này rất hiệu quả và theo các thử nghiệm của tôi, nó nhanh hơn đáng kể so với tùy chọn 1 sử dụng

import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
8 với
import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
9.

Hãy cùng xem một số ví dụ:

import os 
dir_path='C:/route/to/dir'

# Example 1:
num=0
for element in os.scandir[dir_path]:
    if element.is_file[]:   # each time element is a diferent os.DirEntry objetc inside the diretory
        num+=1
print[num]    
# The result is 3

# Example 2 [a more compact form]
print[sum[1 for element in os.scandir[dir_path] if element.is_file[]]]   
# The result is 3

Kết quả trong cả hai trường hợp là 3 vì phương pháp này không đệ quy và không tính

def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
8 bên trong thư mục con ____ ____25

Phương pháp 2: Sử dụng Os.Scandir []

Đây là một phương pháp không nhận được.

Hàm

import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
0 của mô -đun
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
0 trả về một trình lặp lại của các đối tượng
import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
2. Mỗi phần tử chứa trong thư mục được chỉ định sẽ được biểu thị bằng một đối tượng
import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
2 ngoài đường dẫn còn chứa các thuộc tính khác của cùng một.

Do đó, tận dụng thông tin này, chúng tôi sẽ biết liệu một cái gì đó có phải là một tệp hay không bằng cách áp dụng

import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
4 của mô -đun
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
0 mà không cần phải sử dụng hàm
def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
7 của mô -đun
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
2.

  • Phương pháp này rất hiệu quả và theo các thử nghiệm của tôi, nó nhanh hơn đáng kể so với tùy chọn 1 sử dụng
    import os, os.path
    dir_path='C:/route/to/dir'
    
    # Example 1
    num=0
    for element in os.listdir[dir_path]:
        element_path=os.path.join[dir_path, element]
        # os.listdir return only names and we use os.path.join to concatenate the entire route
        # os.path.join will concatenate intellegently the route according with your operating system format
        if os.path.isfile[element_path]:
            num+=1
    print[num]   
    # The result is 3
    
    # Example 2 [a more compact form]
    print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
    # The result is 3
    
    8 với
    import os, os.path
    dir_path='C:/route/to/dir'
    
    # Example 1
    num=0
    for element in os.listdir[dir_path]:
        element_path=os.path.join[dir_path, element]
        # os.listdir return only names and we use os.path.join to concatenate the entire route
        # os.path.join will concatenate intellegently the route according with your operating system format
        if os.path.isfile[element_path]:
            num+=1
    print[num]   
    # The result is 3
    
    # Example 2 [a more compact form]
    print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
    # The result is 3
    
    9.
  • Phương pháp 3: Sử dụng Os.Walk [] - nhanh nhất
  • Phương pháp này có thể được đệ quy hoặc không nhận được.

Hàm mô -đun

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
0
import os 
dir_path='C:/route/to/dir'

# Example 1:
num=0
for element in os.scandir[dir_path]:
    if element.is_file[]:   # each time element is a diferent os.DirEntry objetc inside the diretory
        num+=1
print[num]    
# The result is 3

# Example 2 [a more compact form]
print[sum[1 for element in os.scandir[dir_path] if element.is_file[]]]   
# The result is 3
3 trả về một trình tạo đối tượng. Hàm có thể đi bộ một cây thư mục từ trên xuống dưới, hoặc ngược lại, và đối với mỗi nhánh [hoặc thư mục con], nó trả về một tuple chứa tất cả các tên thư mục con và tệp của nhánh đó.

Mỗi tuple của mỗi nhánh [cha mẹ] chứa 3 bộ dữ liệu bên trong [trẻ em].

[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]

Tuple đứa trẻ đầu tiên chứa tên của thư mục cơ sở của nhánh.

[[subdir], [], file4.txt]

Tuple đứa trẻ thứ hai chứa tên của tất cả các thư mục con trong thư mục chi nhánh hoặc cơ sở.

Tuple đứa trẻ thứ ba chứa tất cả các tệp trong thư mục cơ sở.

Trong ví dụ của chúng tôi, các đối tượng được tạo bởi

import os 
dir_path='C:/route/to/dir'

# Example 1:
num=0
for element in os.scandir[dir_path]:
    if element.is_file[]:   # each time element is a diferent os.DirEntry objetc inside the diretory
        num+=1
print[num]    
# The result is 3

# Example 2 [a more compact form]
print[sum[1 for element in os.scandir[dir_path] if element.is_file[]]]   
# The result is 3
3 là hai bộ dữ liệu vì có nhánh chính có thư mục cơ sở là ____ ____24 và là nhánh thứ hai có thư mục cơ sở là ____ ____25.

Điều đó có nghĩa là, bộ tuple đầu tiên là:

import os
dir_path='C:/route/to/dir'

# Example 1: Non-recursive
tree=os.walk[dir_path, topdown=True]
top_branch=next[tree]
print[len[top_branch[2]]]   
# The result is 3

# Example 2: Non-recursive [a more compact form]
tree=os.walk[dir_path, topdown=True]
print[len[next[tree][2]]]   
# The result is 3  

# Example 4: Recursive
num=0
for i in os.walk[dir_path, topdown=True]:
    num += len[i[2]] 
print[num]   
# The result is 4

và cái thứ hai: & nbsp;Note: In my tests with about 10000 files this method, in both cases, recursive and non-recursive, was the fastest  

Phương pháp 4: Sử dụng glob.iglob [] và os.path.isfile []

Phương pháp này có thể được đệ quy hoặc không nhận được.

Mô -đun

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
1 là cụ thể để tìm các tệp và thư mục có tên khớp với một mẫu, chẳng hạn như tất cả các kết thúc trong
import os 
dir_path='C:/route/to/dir'

# Example 1:
num=0
for element in os.scandir[dir_path]:
    if element.is_file[]:   # each time element is a diferent os.DirEntry objetc inside the diretory
        num+=1
print[num]    
# The result is 3

# Example 2 [a more compact form]
print[sum[1 for element in os.scandir[dir_path] if element.is_file[]]]   
# The result is 3
9. Ở đây chúng tôi sử dụng chức năng
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
0 của mô -đun này trả về trình lặp với tất cả các trận đấu.

Như trong trường hợp này, chúng tôi muốn phù hợp hoàn toàn mọi thứ, chúng tôi đặt một dấu hoa thị

def fileCount[folder]:
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir[folder]:
        path = os.path.join[folder, filename]

        if os.path.isfile[path]:
            count += 1
        elif os.path.isfolder[path]:
            count += fileCount[path]

    return count
5 ở cuối đường dẫn.

Để làm điều tương tự nhưng đệ quy, chúng tôi chỉ định trong đối số [

[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
2] nhưng chúng tôi cũng đặt [nó là cần thiết] Double Asterisk
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
3 ở cuối đường dẫn.

Để phân biệt giữa các thư mục và tệp, chúng tôi sử dụng hàm

def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
7 của mô -đun
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
2 như trong Phương pháp 1.Method 1.

Hãy nhớ rằng, như được giải thích trong tài liệu của mình,

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
1 sẽ không khớp các tệp có tên bắt đầu bằng một khoảng thời gian [chẳng hạn như
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
7 trong ví dụ của chúng tôi]. Nếu đây là một vấn đề thay vì sử dụng
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
8, bạn có thể sử dụng hàm
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
9 của mô -đun
[[subdir], [], file4.txt]
0 nhưng nó sẽ không cho phép đệ quy.

Hiệu suất: Ngoài ra, như tài liệu

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
1 cảnh báo, sử dụng dấu hoa thị kép có thể là một khoảng thời gian không phù hợp. Đây là những gì tôi nhận thấy trong các bài kiểm tra của mình: Không có đệ quy và với khoảng 300 tệp, nó mất thời gian tương tự như Phương pháp 1, nhưng với đệ quy với khoảng 10000 tệp, nó rất chậm mất khoảng 3,5 giây, chắc chắn không được khuyến nghị cho những trường hợp này.Performance: Also, as the
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
1 documentation warns, using the double asterisk can be an inordinate amount of time. This is what I noticed in my tests: without recursion and with about 300 files it took similar times to method 1, but with recursion with about 10000 files, it was very slow taking around 3.5 seconds, definitely not recommended for these cases.

Hãy cùng xem một số ví dụ:

import glob, os.path

# Example 1: Non-recursive
dir_path='C:/route/to/dir/*'   # Route with one asterisk
num=0
for i in glob.iglob[dir_path,recursive=False]:
    if os.path.isfile[i]:
        num+=1
print[num]   
# The Result is 2 [exclude .file1.txt that start with a dot]

# Example 2: Non-recursive [a more compact form]
print[num=sum[1 for i in glob.iglob[dir_path,recursive=False] if os.path.isfile[i]]]

# Example 3: Recursive
dir_path='C:/route/to/dir/**'   # Route with two asterisk
num=0
for i in glob.iglob[dir_path,recursive=True]:
    if os.path.isfile[i]:
        num+=1
print['num: ', num]   
# The Result is 3 [exclude .file1.txt that start with a dot]

# Example 4: Recursive [a more compact form]
num=sum[1 for i in glob.iglob[dir_path,recursive=True] if os.path.isfile[i]]
print[num]   
# The Result is 3 [exclude .file1.txt that start with a dot]

Phương pháp 5: Sử dụng pathlib.path []

Phương pháp này có thể được đệ quy hoặc không nhận được.

Mô -đun

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
1 là cụ thể để tìm các tệp và thư mục có tên khớp với một mẫu, chẳng hạn như tất cả các kết thúc trong
import os 
dir_path='C:/route/to/dir'

# Example 1:
num=0
for element in os.scandir[dir_path]:
    if element.is_file[]:   # each time element is a diferent os.DirEntry objetc inside the diretory
        num+=1
print[num]    
# The result is 3

# Example 2 [a more compact form]
print[sum[1 for element in os.scandir[dir_path] if element.is_file[]]]   
# The result is 3
9. Ở đây chúng tôi sử dụng chức năng
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
0 của mô -đun này trả về trình lặp với tất cả các trận đấu.

Như trong trường hợp này, chúng tôi muốn phù hợp hoàn toàn mọi thứ, chúng tôi đặt một dấu hoa thị

def fileCount[folder]:
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir[folder]:
        path = os.path.join[folder, filename]

        if os.path.isfile[path]:
            count += 1
        elif os.path.isfolder[path]:
            count += fileCount[path]

    return count
5 ở cuối đường dẫn.Method 1 and
[[subdir], [], file4.txt]
4 has some similarity with the
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
0 function of the
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
1 module that we used in Method 4.

Để làm điều tương tự nhưng đệ quy, chúng tôi chỉ định trong đối số [

[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
2] nhưng chúng tôi cũng đặt [nó là cần thiết] Double Asterisk
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
3 ở cuối đường dẫn.

Để phân biệt giữa các thư mục và tệp, chúng tôi sử dụng hàm

def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
7 của mô -đun
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
2 như trong Phương pháp 1.

Hãy nhớ rằng, như được giải thích trong tài liệu của mình,

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
1 sẽ không khớp các tệp có tên bắt đầu bằng một khoảng thời gian [chẳng hạn như
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
7 trong ví dụ của chúng tôi]. Nếu đây là một vấn đề thay vì sử dụng
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
8, bạn có thể sử dụng hàm
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
9 của mô -đun
[[subdir], [], file4.txt]
0 nhưng nó sẽ không cho phép đệ quy.

Hiệu suất: Ngoài ra, như tài liệu

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
1 cảnh báo, sử dụng dấu hoa thị kép có thể là một khoảng thời gian không phù hợp. Đây là những gì tôi nhận thấy trong các bài kiểm tra của mình: Không có đệ quy và với khoảng 300 tệp, nó mất thời gian tương tự như Phương pháp 1, nhưng với đệ quy với khoảng 10000 tệp, nó rất chậm mất khoảng 3,5 giây, chắc chắn không được khuyến nghị cho những trường hợp này.

def fileCount[folder]:
    "count the number of files in a directory"

    count = 0

    for filename in os.listdir[folder]:
        path = os.path.join[folder, filename]

        if os.path.isfile[path]:
            count += 1
        elif os.path.isfolder[path]:
            count += fileCount[path]

    return count
0

Hãy cùng xem một số ví dụ:

Phương pháp 5: Sử dụng pathlib.path []

Ở đây chúng tôi sử dụng cơ bản mô -đun

from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
3. Cụ thể, chúng tôi sử dụng các hàm
[[subdir], [], file4.txt]
3,
[[subdir], [], file4.txt]
4 và
import os, os.path
dir_path='C:/route/to/dir'

# Example 1
num=0
for element in os.listdir[dir_path]:
    element_path=os.path.join[dir_path, element]
    # os.listdir return only names and we use os.path.join to concatenate the entire route
    # os.path.join will concatenate intellegently the route according with your operating system format
    if os.path.isfile[element_path]:
        num+=1
print[num]   
# The result is 3

# Example 2 [a more compact form]
print[sum[[1 for element in os.listdir[dir_path] if os.path.isfile[os.path.join[dir_path, element]]]]]   
# The result is 3
4 của lớp
[[subdir], [], file4.txt]
6.

Hàm

[[subdir], [], file4.txt]
3 có một số tương đương với hàm
def fileCount[folder, allowed_extensions=None]:
   "count the number of files in a directory and sub directory"
   count = 0
   for base, dirs, files in os.walk[folder]:
      for file in files:
         if allowed_extensions and file.endswith[allowed_extensions] or not allowed_extensions:
            count += 1
   return count
2 của mô -đun
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
0 mà chúng tôi đã sử dụng trong Phương pháp 1 và
[[subdir], [], file4.txt]
4 có một số điểm tương đồng với hàm
[[dir],[subdir],[.file1.txt, file2.png, file3.lnk]]
0 của mô -đun
from pathlib import Path

total_dir_files = len[list[Path.cwd[].rglob['*']]]

# or 
total_dir_files = len[[*Path.cwd[].rglob['*']]]

# or filter for only files using is_file[]
file_count = len[[f for f in Path.cwd[].rglob['*'] if f.is_file[]]]
1 mà chúng tôi sử dụng trong Phương pháp 4.

Bài Viết Liên Quan

Chủ Đề