Làm cách nào để tìm kiếm tệp có tên cụ thể trong python?

Xây dựng vấn đề. Giả sử chúng ta có một thư mục chứa các thư mục con khác chứa các tệp khác. Làm cách nào để chúng tôi tìm kiếm một tệp cụ thể trong các thư mục con trong tập lệnh Python của chúng tôi?

Kịch bản. Chúng tôi có một thư mục mẹ (

import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
1) với các thư mục con (
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
2,
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
3 và
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
4). Có các tệp trong thư mục/thư mục mẹ cũng như các thư mục con. Chúng tôi chỉ cần tìm các tệp
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
5 chỉ có trong các thư mục con, tôi. e. ,
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
6,
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
7 và
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
8 và bỏ qua các tệp có trong thư mục mẹ và bất kỳ tệp nào khác có phần mở rộng khác. Chúng ta nên tiếp cận kịch bản này như thế nào?

Hãy xem nhanh cấu trúc thư mục mà chúng ta phải xử lý

________số 8

Vấn đề ban đầu có vẻ khó khăn, nhưng nó có thể được giải quyết dễ dàng vì Python cung cấp cho chúng ta nhiều thư viện và mô-đun để xử lý các thư mục, thư mục con và tệp chứa trong chúng. Vì vậy, không chậm trễ hơn nữa, chúng ta hãy đi sâu vào các giải pháp cho câu hỏi quan trọng về sứ mệnh của chúng ta

🖊️Lưu ý quan trọng. Mỗi giải pháp quan tâm đến một vài điểm chính.
i. Làm cách nào để chỉ chọn các tệp thư mục con và loại bỏ các tệp thư mục mẹ?
ii. Làm cách nào để chỉ chọn các tệp cụ thể (tức là tệp

import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
5 trong trường hợp này) và loại bỏ các tệp khác trong thư mục con?

📹Video hướng dẫn

Làm cách nào để chỉ tìm kiếm các tệp cụ thể trong các thư mục con trong Python?

Làm cách nào để tìm kiếm tệp có tên cụ thể trong python?

Xem video này trên YouTube

Phương pháp 1. Sử dụng hệ điều hành. đi bộ + kết thúc + tham gia

Tóm tắt nhanh các điều kiện tiên quyết

  • import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    00 là một chức năng của mô-đun
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    01 trong Python về cơ bản trả về một danh sách gồm ba điều -
    1. Tên của thư mục gốc
    2. Danh sách tên của các thư mục con
    3. Danh sách tên tệp trong thư mục hiện tại.  
  • import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    02 là một phương thức tích hợp sẵn trong Python trả về
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    03 hoặc
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    04 tùy thuộc vào việc chuỗi có kết thúc bằng một giá trị được chỉ định hay không
  • Hàm
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    05 cho phép chúng ta nối các phần tử trong một lần lặp nhất định

Cách tiếp cận

  • Ý tưởng là sử dụng phương thức
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    00 và tìm nạp các thư mục con và tệp trong các thư mục con đối với thư mục mẹ
  • Nếu thư mục được trích xuất không phải là thư mục gốc/thư mục mẹ, thì chúng tôi lặp lại tất cả các tệp trong thư mục con. Đồng thời, chúng tôi kiểm tra xem tệp có kết thúc bằng phần mở rộng
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    5 hay không với sự trợ giúp của phương thức kết thúc
  • Nếu đúng, thì chúng tôi chỉ cần trả lại tên tệp. Để lấy đường dẫn của tệp,
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    08 đường dẫn của thư mục con và tên tệp

Mã số

import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))

đầu ra

import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
0

Phương pháp 2. Sử dụng hệ điều hành. danh sách dir + hệ điều hành. đường dẫn. isdir + endwith

điều kiện tiên quyết. Chúng tôi đã tìm hiểu về các phương pháp

import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
09 và
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
08 trong giải pháp trước. Chúng ta hãy xem nhanh một số phương pháp khác sẽ giúp chúng ta trong phương pháp này

  • import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    31 là một phương thức của mô-đun
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    01 liệt kê tất cả các tệp và thư mục con có trong một thư mục được chỉ định
  • import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    33 là một phương thức khác của mô-đun
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    01 dùng để kiểm tra xem một đường dẫn đã chỉ định có phải là một thư mục hiện có hay không
  • import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    35 tương tự như phương thức
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    36, với điểm khác biệt duy nhất là nó kiểm tra xem đường dẫn đã cho có phải là tệp thông thường hiện có hay không

Cách tiếp cận

  • Lặp lại tất cả các thư mục con và tệp có trong thư mục mẹ với sự trợ giúp của hàm
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    37
  • Kiểm tra xem một thành phần trong thư mục mẹ có phải là thư mục con hay không. Nếu có, hãy lặp lại tất cả các thư mục con và kiểm tra thêm xem nội dung trong thư mục con có phải là tệp hay không
  • Nếu đó là một tệp, hãy kiểm tra xem tệp có kết thúc bằng phần mở rộng
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    5 hay không và sau đó hiển thị tên tệp cùng với đường dẫn của nó
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
3

đầu ra

import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
0

Phương pháp 3. Sử dụng hệ điều hành. scandir + hệ điều hành. listdir + endwith()

Ghi chú. Hệ điều hành. scandir() được giới thiệu trong Python 3. 5 và là một trong những phương thức mới nhất trong Python cho phép chúng ta liệt kê tất cả các tệp trong một thư mục. Phương pháp này không trả về một danh sách;

Cách tiếp cận

  • Liệt kê tất cả nội dung (tệp và thư mục) trong thư mục mẹ với sự trợ giúp của phương thức
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    39
  • Kiểm tra xem nội dung có phải là thư mục con hay không. Nếu đó là một thư mục, hãy tìm danh sách tất cả các tệp có trong thư mục con
  • Kiểm tra xem tệp có kết thúc bằng phần mở rộng
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    5 hay không. Nếu có, hiển thị tên của tệp và đường dẫn của tệp
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
5

đầu ra

import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
6

Phương pháp 4. Sử dụng Pathlib

Cách tiếp cận

  • Ý tưởng ở đây là sử dụng mô-đun
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    01 của Python để lặp lại các nội dung hiện có trong thư mục mẹ.
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    02
  • Kiểm tra xem nội dung có phải là một thư mục hay không. Nếu đó là một thư mục, thì hãy sử dụng phương thức
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    03 của mô-đun pathlib để kiểm tra xem thư mục con đó có các tệp kết thúc bằng phần mở rộng
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    5 hay không
  • Cuối cùng, hiển thị tên tệp cùng với đường dẫn của nó như hình bên dưới
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
1

đầu ra

import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
0

Phương pháp 5. Sử dụng toàn cầu

 Mô-đun toàn cục trong Python là một mô-đun rất hiệu quả có một số chức năng tích hợp nhất định giúp chúng tôi có khả năng liệt kê các tệp cụ thể trong một thư mục. quả địa cầu. glob() là một trong số hàm đó cung cấp các ký tự đại diện như “*”, “?”, [ranges]  giúp quá trình truy xuất đường dẫn trở nên dễ dàng

Cách tiếp cận

  • Sử dụng
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    05 để cho phép Python tìm kiếm đệ quy các thư mục con hiện có
  • import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    06 đảm bảo rằng tất cả các thư mục con đều phù hợp và
    import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    07 được sử dụng để chỉ định loại tệp đang được tìm kiếm
  • import os
    
    root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
    for folder, subfolders, files in os.walk(root_dir):
        if folder != root_dir:
            for f in files:
                if f.endswith(".csv"):
                    print("File Name: ", f)
                    print(f"Path: ", os.path.join(folder, f))
    03 chỉ cần trả về đường dẫn của tệp. Để lấy tên tệp, bạn có thể chia toàn bộ chuỗi đường dẫn thành một danh sách và lấy phần tử cuối cùng từ danh sách, phần tử này sẽ chứa tên tệp
import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
7

đầu ra

import os

root_dir = r"C:\Users\SHUBHAM SAYON\Desktop\Parent"
for folder, subfolders, files in os.walk(root_dir):
    if folder != root_dir:
        for f in files:
            if f.endswith(".csv"):
                print("File Name: ", f)
                print(f"Path: ", os.path.join(folder, f))
0

Sự kết luận

Tốt. Chúng tôi đã thảo luận nhiều nhất là năm phương pháp để giải quyết vấn đề đã cho. Tuy nhiên, đây là danh sách các bài báo rất được đề xuất nếu bạn muốn tìm hiểu sâu hơn về các vấn đề như thế này –

  • Tìm tất cả các tệp trong một thư mục có phần mở rộng. txt bằng Python
  • Làm cách nào để liệt kê tất cả các tệp của một thư mục trong Python?
  • Làm cách nào để lấy tên tệp mà không cần phần mở rộng từ đường dẫn trong Python?
  • Cách Pythonic nhất để kiểm tra xem tệp có tồn tại trong Python không

Hãy theo dõi để biết thêm các bài viết và thảo luận thú vị. học tập vui vẻ

Làm cách nào để tìm kiếm tệp có tên cụ thể trong python?

Shubham Sayon

Tôi là một người tạo nội dung và Blogger Python chuyên nghiệp. Tôi đã xuất bản nhiều bài báo và tạo các khóa học trong một khoảng thời gian. Hiện tại tôi đang làm việc với tư cách là một freelancer toàn thời gian và tôi có kinh nghiệm trong các lĩnh vực như Python, AWS, DevOps và Networking