Hướng dẫn check folder empty python - kiểm tra thư mục python trống

Tôi đang cố gắng kiểm tra xem một thư mục có trống không và làm như sau:

import os
downloadsFolder = '../../Downloads/'
if not os.listdir(downloadsFolder):
    print "empty"
else:
    print "not empty"

Thật không may, tôi luôn nhận được "không trống" "bất kể tôi có bất kỳ tệp nào trong thư mục đó hay không. Có phải vì có thể có một số tệp hệ thống ẩn? Có cách nào để sửa đổi mã trên để kiểm tra chỉ cho các tệp không ẩn không?

Đã hỏi ngày 14 tháng 3 năm 2018 lúc 17:19Mar 14, 2018 at 17:19

Hướng dẫn check folder empty python - kiểm tra thư mục python trống

4

Bạn có thể sử dụng hai phương pháp này từ mô -đun HĐH.

Lựa chọn đầu tiên:

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")

Tùy chọn thứ hai (như một danh sách trống đánh giá thành

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
4 trong Python):

import os
if not os.listdir('/your/path'):
    print("Directory is empty")
else:    
    print("Directory is not empty")

Tuy nhiên,

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
5 có thể ném một ngoại lệ, ví dụ như khi đường dẫn đã cho không tồn tại. Do đó, bạn cần phải bao gồm điều này.

import os
dir_name = '/your/path'
if os.path.isdir(dir_name):
    if not os.listdir(dir_name):
        print("Directory is empty")
    else:    
        print("Directory is not empty")
else:
    print("Given directory doesn't exist")

Tôi hy vọng nó sẽ hữu ích cho bạn.

Nguồn: http://web.archive.org/web/20180531030548/http://thispinter.com/python-how-to-check-if-a-directory-is-empty

Đã trả lời ngày 26 tháng 11 năm 2019 lúc 12:03Nov 26, 2019 at 12:03

Hướng dẫn check folder empty python - kiểm tra thư mục python trống

2

Kể từ Python 3.5+,

with os.scandir(path) as it:
    if any(it):
        print('not empty')

thường hoạt động nhanh hơn

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
6 vì
import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
7 là một trình lặp và không sử dụng một số chức năng nhất định để nhận số liệu thống kê trên một tệp nhất định.

Đã trả lời ngày 4 tháng 3 năm 2021 lúc 19:01Mar 4, 2021 at 19:01

FlairflairFlair

2.3631 Huy hiệu vàng26 Huy hiệu bạc39 Huy hiệu đồng1 gold badge26 silver badges39 bronze badges

6

Hmm, tôi vừa thử mã của bạn thay đổi đường dẫn thành một thư mục trống và nó đã in "trống" cho tôi, vì vậy phải có các tệp ẩn trong các bản tải xuống của bạn. Bạn có thể thử lặp qua tất cả các tệp và kiểm tra xem chúng có bắt đầu với '.' hay không.

EDIT:

Thử cái này. Nó làm việc cho tôi.

if [f for f in os.listdir(downloadsFolder) if not f.startswith('.')] == []:
    print "empty"
else: 
    print "not empty"

Đã trả lời ngày 14 tháng 3 năm 2018 lúc 17:30Mar 14, 2018 at 17:30

Algricealgricealgrice

2291 Huy hiệu bạc4 Huy hiệu đồng1 silver badge4 bronze badges

1

Hãy thử:

import os
dirContents = os.listdir(downloadsFolder)
if not dirContents:
    print('Folder is Empty')
else:
    print('Folder is Not Empty')

Hướng dẫn check folder empty python - kiểm tra thư mục python trống

Đã trả lời ngày 4 tháng 1 năm 2019 lúc 7:34Jan 4, 2019 at 7:34

Sspsujitsspsujitsspsujit

3014 Huy hiệu bạc11 Huy hiệu đồng4 silver badges11 bronze badges

1

Như đã đề cập bởi Muskaya ở đây. Bạn cũng có thể sử dụng pathlib. Tuy nhiên, nếu bạn chỉ muốn kiểm tra, nếu thư mục trống hay không, bạn nên kiểm tra trình trả lời này:

from pathlib import Path

def directory_is_empty(directory: str) -> bool:
    return not any(Path(directory).iterdir())


downloadsFolder = '../../Downloads/'
if directory_is_empty(downloadsFolder):
    print "empty"
else:
    print "not empty"

Đã trả lời ngày 13 tháng 1 lúc 13:08Jan 13 at 13:08

Hướng dẫn check folder empty python - kiểm tra thư mục python trống

RenereneRene

7651 Huy hiệu vàng10 Huy hiệu bạc24 Huy hiệu đồng1 gold badge10 silver badges24 bronze badges

Mở rộng câu trả lời của @Flair với xử lý lỗi:

Bạn có thể sử dụng

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
8:

from os import scandir


def is_non_empty_dir(dir_name: str) -> bool:
    """
    Returns True if the directory exists and contains item(s) else False
    """
    try:
        if any(scandir(dir_name)):
            return True
    except (NotADirectoryError, FileNotFoundError):
        pass
    return False

Đã trả lời ngày 9 tháng 12 năm 2021 lúc 6:46Dec 9, 2021 at 6:46

5

Tôi nghĩ bạn có thể thử mã này:

directory = r'path to the directory'

from os import walk

f = [] #to list the files

d = [] # to list the directories


for (dirpath, dirnames, filenames) in walk(directory):

    f.extend(filenames)
    d.extend(dirnames)
    break

if len(f) and len(d) != 0:
    print('Not empty')
else:
    print('empty')

Đã trả lời ngày 14 tháng 3 năm 2018 lúc 17:36Mar 14, 2018 at 17:36

Hướng dẫn check folder empty python - kiểm tra thư mục python trống

Bạn có thể sử dụng phần sau để xác thực rằng không có tệp nào tồn tại bên trong thư mục đầu vào:

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
0

Hướng dẫn check folder empty python - kiểm tra thư mục python trống

Dharman ♦

28.3K21 Huy hiệu vàng75 Huy hiệu bạc128 Huy hiệu đồng21 gold badges75 silver badges128 bronze badges

Đã trả lời ngày 18 tháng 1 lúc 22:48Jan 18 at 22:48

Một phiên bản khác:

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
1

Đã trả lời ngày 26 tháng 2 năm 2021 lúc 19:37Feb 26, 2021 at 19:37

Tomas G.Tomas G.Tomas G.

3.27624 Huy hiệu bạc24 Huy hiệu đồng24 silver badges24 bronze badges

TLDR (cho Python 3.10.4):

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
9

Đây là một bản demo nhanh:

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
2

Đã trả lời ngày 31 tháng 5 lúc 3:37May 31 at 3:37

Hướng dẫn check folder empty python - kiểm tra thư mục python trống

OrenishshalomorenishshalomOrenIshShalom

5.0886 Huy hiệu vàng25 Huy hiệu bạc74 Huy hiệu đồng6 gold badges25 silver badges74 bronze badges

Trong HĐH Python, có một hàm gọi là

import os
if not os.listdir('/your/path'):
    print("Directory is empty")
else:    
    print("Directory is not empty")
0, trả về một mảng nội dung tệp của thư mục đã cho. Vì vậy, nếu mảng trống, điều đó có nghĩa là không có tệp trong thư mục.

Đây là một đoạn mã;

import os
if len(os.listdir('/your/path')) == 0:
    print("Directory is empty")
else:    
    print("Directory is not empty")
3

Hy vọng đây là những gì bạn đang tìm kiếm.

Hướng dẫn check folder empty python - kiểm tra thư mục python trống

Đã trả lời ngày 14 tháng 3 năm 2018 lúc 17:26Mar 14, 2018 at 17:26

Rob Grob gRob G

Phù hiệu bằng đồng 2133 bronze badges

1