Hướng dẫn how do i search for a filename in python? - làm cách nào để tìm kiếm tên tệp trong python?

Câu trả lời của @F.M.F có một vài vấn đề trong phiên bản này, vì vậy tôi đã thực hiện một vài điều chỉnh để làm cho nó hoạt động.

import os
from os import scandir
import ctypes

def is_sym_link(path):
    # http://stackoverflow.com/a/35915819
    FILE_ATTRIBUTE_REPARSE_POINT = 0x0400
    return os.path.isdir(path) and (ctypes.windll.kernel32.GetFileAttributesW(str(path)) & FILE_ATTRIBUTE_REPARSE_POINT)

def find(base, filenames):
    hits = []

    def find_in_dir_subdir(direc):
        content = scandir(direc)
        for entry in content:
            if entry.name in filenames:
                hits.append(os.path.join(direc, entry.name))

            elif entry.is_dir() and not is_sym_link(os.path.join(direc, entry.name)):
                try:
                    find_in_dir_subdir(os.path.join(direc, entry.name))
                except UnicodeDecodeError:
                    print("Could not resolve " + os.path.join(direc, entry.name))
                    continue
                except PermissionError:
                    print("Skipped " + os.path.join(direc, entry.name) + ". I lacked permission to navigate")
                    continue

    if not os.path.exists(base):
        return
    else:
        find_in_dir_subdir(base)

    return hits

unicode () đã được thay đổi thành str () trong python 3, vì vậy tôi đã thực hiện điều chỉnh đó (dòng 8)

Tôi cũng đã thêm (trong dòng 25) và ngoại lệ cho PernessError. Bằng cách này, chương trình sẽ không dừng lại nếu tìm thấy một thư mục mà nó không thể truy cập.

Cuối cùng, tôi muốn đưa ra một cảnh báo nhỏ. Khi chạy chương trình, ngay cả khi bạn đang tìm kiếm một tệp/thư mục duy nhất, hãy đảm bảo bạn chuyển nó dưới dạng danh sách. Nếu không, bạn sẽ nhận được rất nhiều câu trả lời không nhất thiết phải phù hợp với tìm kiếm của bạn.

Ví dụ về việc sử dụng:

Tìm ("C: \", ["Python", "bài tập về nhà"])

hoặc

Tìm ("C: \\", ["Bài tập về nhà"])

Nhưng, ví dụ: Tìm ("C: \\", "bài tập về nhà") sẽ đưa ra câu trả lời không muốn.

Tôi sẽ nói dối nếu tôi nói tôi biết tại sao điều này xảy ra. Một lần nữa, đây không phải là mã của tôi và tôi chỉ thực hiện các điều chỉnh tôi cần để làm cho nó hoạt động. Tất cả tín dụng nên được chuyển đến @f.m.f.


Python có thể tìm kiếm tên tệp trong một đường dẫn được chỉ định của HĐH. Điều này có thể được thực hiện bằng cách sử dụng HĐH mô -đun với các chức năng đi bộ (). Điều này sẽ lấy một đường dẫn cụ thể làm đầu vào và tạo ra 3-tuple liên quan đến dirpath, dirnames và tên tệp.

Trong ví dụ dưới đây, chúng tôi đang tìm kiếm một tệp có tên SMPL.htm bắt đầu tại thư mục gốc có tên là D D: \. Hàm os.walk () tìm kiếm toàn bộ thư mục và từng thư mục con của nó để xác định vị trí tệp này. Kết quả là chúng tôi thấy rằng tệp có mặt trong cả thư mục chính và cả trong một thư mục con. Chúng tôi đang chạy chương trình này trong HĐH Windows.

Thí dụ

import os

def find_files(filename, search_path):
   result = []

# Wlaking top-down from the root
   for root, dir, files in os.walk(search_path):
      if filename in files:
         result.append(os.path.join(root, filename))
   return result

print(find_files("smpl.htm","D:"))

Đầu ra

Chạy mã trên cho chúng ta kết quả sau -

['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']

Hướng dẫn how do i search for a filename in python? - làm cách nào để tìm kiếm tên tệp trong python?

Cập nhật vào ngày 17 tháng 10 năm 2019 12:44:29

  • Câu hỏi và câu trả lời liên quan
  • Tìm kiếm tệp bằng C#
  • Kết hợp so với tìm kiếm trong Python
  • Làm thế nào để tìm kiếm từ điển Python hoạt động?
  • Xử lý tệp netrc bằng cách sử dụng python
  • Tìm kiếm mẫu ngây thơ
  • Đọc và viết tệp CSV bằng Python
  • Làm thế nào để tìm một tệp bằng Python?
  • Làm thế nào để trích xuất tiện ích mở rộng tệp bằng Python?
  • Làm thế nào để đổi tên một tệp bằng Python?
  • Làm thế nào để xóa một tệp bằng Python?
  • Làm thế nào để xóa một tệp bằng Python?
  • Chương trình C ++ để thực hiện tìm kiếm bằng danh sách tự tổ chức
  • Tìm kiếm một truy vấn bằng tìm kiếm nhị phân trong JavaScript
  • Làm thế nào để tạo một tệp trùng lặp của một tệp hiện có bằng Python?
  • Giới thiệu về Thuật toán tìm kiếm

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc
    This code searches all the folders in the file it’s being run. If you want some other kinds of files just change the extension.
     

    Python3

    import os

    dir_path = os.path.dirname(os.path.realpath(__file__))

    for root, dirs, files

    import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    0
    import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    1

    import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    2for
    import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    4
    import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    0
    import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    6

    import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    7
    import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    8
    import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    4
    ['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
    0
    ['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
    1
    ['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
    2

    ['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
    3
    ['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
    4
    ['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
    5
    ['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
    6
    ['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
    7
    ['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
    6
    ['D:TP\smpl.htm', 'D:TP\spyder_pythons\smpl.htm']
    9________________
    import os
    
    def find_files(filename, search_path):
       result = []
    
    # Wlaking top-down from the root
       for root, dir, files in os.walk(search_path):
          if filename in files:
             result.append(os.path.join(root, filename))
       return result
    
    print(find_files("smpl.htm","D:"))
    4import2

    HĐH không phải là một thư viện bên ngoài trong Python. Vì vậy, tôi cảm thấy đây là cách đơn giản nhất và tốt nhất để làm điều này. Bài viết này được đóng góp bởi Soumith Kumar. Nếu bạn thích GeekSforGeeks và muốn đóng góp, bạn cũng có thể viết một bài viết bằng Write.GeekSforGeek.org hoặc gửi bài viết của bạn. Xem bài viết của bạn xuất hiện trên trang chính của GeekSforGeek và giúp các chuyên viên máy tính khác. Xin vui lòng viết nhận xét nếu bạn tìm thấy bất cứ điều gì không chính xác hoặc bạn muốn chia sẻ thêm thông tin về chủ đề được thảo luận ở trên. & NBSP;
    This article is contributed by soumith kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.
    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
     

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

    Sử dụng glob.glob () để tìm kiếm các tệp cụ thể trong các thư mục con trong Python.Gọi Quả cầu.GLOB (PathName, Recursive = true) với tên đường dẫn như một đường dẫn đến một thư mục và đệ quy là đúng để cho phép tìm kiếm đệ quy thông qua các thư mục con hiện có. glob() to search for specific files in subdirectories in Python. Call glob. glob(pathname, recursive=True) with pathname as a path to a directory and recursive as True to enable recursively searching through existing subdirectories.

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

    Sử dụng hàm os.listdir () HĐH.Hàm ListDIR ('Path') trả về một danh sách chứa tên của các tệp và thư mục có trong thư mục được đưa ra bởi đường dẫn. The os. listdir('path') function returns a list containing the names of the files and directories present in the directory given by the path .