ví dụ 1. sử dụng toàn cầu
import glob, os
os.chdir["my_dir"]
for file in glob.glob["*.txt"]:
print[file]
đầu ra
c.txt b.txt a.txt
Sử dụng mô-đun glob
, bạn có thể tìm kiếm các tệp có phần mở rộng nhất định
os.chdir["my_dir"]
đặt thư mục làm việc hiện tại thành/my_dir
- Sử dụng vòng lặp for, bạn có thể tìm kiếm các tệp có phần mở rộng
.txt
bằng cách sử dụngc.txt b.txt a.txt
0 c.txt b.txt a.txt
1 biểu thị tất cả các tệp có phần mở rộng nhất định
ví dụ 2. Sử dụng hệ điều hành
import os
for file in os.listdir["my_dir"]:
if file.endswith[".txt"]:
print[file]
đầu ra
a.txt b.txt c.txt
Trong ví dụ này, chúng tôi sử dụng phương pháp
c.txt b.txt a.txt2 để kiểm tra phần mở rộng
.txt
- Sử dụng vòng lặp for, lặp qua từng tệp của thư mục
/my_dir
- Kiểm tra xem tệp có phần mở rộng
.txt
bằng cách sử dụngc.txt b.txt a.txt
2
Sử dụng hệ điều hành. đi bộ
________số 8_______đầu ra
c.txt b.txt a.txt
Ví dụ này sử dụng phương pháp
c.txt b.txt a.txt7 của mô-đun
c.txt b.txt a.txt8
- Sử dụng vòng lặp for, lặp qua từng
c.txt b.txt a.txt
9 của
0import os for file in os.listdir["my_dir"]: if file.endswith[".txt"]: print[file]
- Kiểm tra xem tệp có phần mở rộng
.txt
bằng cách sử dụngc.txt b.txt a.txt
2
Để tìm tất cả các tệp có phần mở rộng cụ thể trong Python, bạn có thể sử dụng hàm
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]2 để duyệt qua cấu trúc thư mục và kiểm tra xem mỗi tệp có phần mở rộng mong muốn hay không bằng cách sử dụng phương pháp
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]3
Ví dụ: hãy tìm tất cả các tệp
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]4
import os for root, dirs, files in os.walk['/path/to/directory']: for file in files: if file.endswith['.txt']: print[os.path.join[root, file]]
Điều này sẽ in đường dẫn đầy đủ của tất cả các tệp có phần mở rộng
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]4 trong thư mục được chỉ định. Bạn có thể thay thế
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]4 bằng bất kỳ phần mở rộng tệp mong muốn nào khác
Nếu bạn đang tìm kiếm một câu trả lời nhanh chóng, tôi chắc chắn những điều trên sẽ làm được
Nhưng nếu bạn đang muốn cải thiện kỹ năng Python của mình và muốn tìm hiểu cách tìm tệp đệ quy trong thư mục có thư mục con, hãy tiếp tục đọc. Hướng dẫn này giới thiệu cho bạn 3 phương pháp khác nhau mà bạn có thể sử dụng để tìm các tệp thuộc một loại cụ thể trong Python
Hãy nhảy vào nó
3 cách để tìm tất cả các tệp theo tiện ích mở rộng trong Python
Có ba cách chính để tìm tất cả các tệp theo phần mở rộng trong Python
- Mô-đun 'toàn cầu'
- các 'os. listdir' chức năng
- các 'os. chức năng đi bộ
Chúng ta hãy xem xét kỹ hơn cách thức hoạt động của từng phương pháp này
1. Mô-đun 'toàn cầu'
Bạn có thể sử dụng mô-đun toàn cầu trong Python để tìm tất cả các tệp có. txt sử dụng đoạn mã sau
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]
Hàm
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]7 tìm kiếm tất cả các tệp trong thư mục hiện tại khớp với mẫu đã chỉ định, trong trường hợp này là
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]8. Điều này yêu cầu chức năng tìm tất cả các tệp có tên kết thúc bằng
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]4. Kết quả là một danh sách tên của các tệp phù hợp
Bạn cũng có thể chỉ định một thư mục khác để tìm kiếm bằng cách chuyển đường dẫn đến thư mục làm đối số đầu tiên cho hàm
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]7. Ví dụ: nếu bạn muốn tìm kiếm tất cả các tệp
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]4 trong thư mục
import glob # Find all files with the .txt extension in the specified directory txt_files = glob.glob['/path/to/directory/*.txt'] # Print the names of the files found print[txt_files]2, hãy chạy lệnh sau
import glob # Find all files with the .txt extension in the specified directory txt_files = glob.glob['/path/to/directory/*.txt'] # Print the names of the files found print[txt_files]
Ví dụ
Đây là một dự án ví dụ tôi có
Hình ảnh trên cho thấy cấu trúc thư mục, nhưng trong trường hợp bạn cần rõ ràng, thì đây là cấu trúc của nó
Hãy tìm tất cả các tệp văn bản [kết thúc bằng ‘. txt’] trong thư mục
Để làm điều này, hãy chạy mã từ phần trước để xem điều gì sẽ xảy ra
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]
đầu ra
['names.txt', 'values.txt']
Nó trả về tệp ‘
import glob # Find all files with the .txt extension in the specified directory txt_files = glob.glob['/path/to/directory/*.txt'] # Print the names of the files found print[txt_files]3‘ và ‘
import glob # Find all files with the .txt extension in the specified directory txt_files = glob.glob['/path/to/directory/*.txt'] # Print the names of the files found print[txt_files]4‘ nhưng không trả về tệp văn bản trong các thư mục con. Để liệt kê các tệp có phần mở rộng cụ thể trong các thư mục con, bạn cần thực hiện phương pháp đệ quy
2. Tìm kiếm đệ quy với 'os. listdir[]'
Như bạn đã thấy trong ví dụ trước, hàm
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]7 chỉ tìm kiếm các tệp trong thư mục đã chỉ định và không tìm kiếm trong bất kỳ thư mục con nào của nó
Để tìm kiếm các tệp có phần mở rộng cụ thể trong thư mục đã chỉ định và tất cả các thư mục con của nó, bạn có thể sử dụng hàm
import glob # Find all files with the .txt extension in the specified directory txt_files = glob.glob['/path/to/directory/*.txt'] # Print the names of the files found print[txt_files]6 theo cách đệ quy
Đây là một triển khai ví dụ
import os def find_files[dir_path, extension]: # Check if the given path is a valid directory if not os.path.isdir[dir_path]: return # Get a list of all the files and directories in the given directory files_and_dirs = os.listdir[dir_path] # Iterate over the list of files and directories for file_or_dir in files_and_dirs: # Construct the full path of the file or directory full_path = os.path.join[dir_path, file_or_dir] # If the full path is a directory, recursively call the function to find the files in that directory if os.path.isdir[full_path]: find_files[full_path, extension] else: # If the full path is a file that ends with extension, print its path if full_path.endswith[extension]: print[full_path]
Đoạn mã này định nghĩa một hàm đệ quy có tên là
import glob # Find all files with the .txt extension in the specified directory txt_files = glob.glob['/path/to/directory/*.txt'] # Print the names of the files found print[txt_files]7 lấy một đường dẫn thư mục làm đối số và tìm kiếm các tệp trong thư mục đó và tất cả các thư mục con của nó
Nó sử dụng hàm
import glob # Find all files with the .txt extension in the specified directory txt_files = glob.glob['/path/to/directory/*.txt'] # Print the names of the files found print[txt_files]6 để lấy tên của tất cả các tệp và thư mục trong thư mục đã chỉ định, sau đó sử dụng hàm
import glob # Find all files with the .txt extension in the specified directory txt_files = glob.glob['/path/to/directory/*.txt'] # Print the names of the files found print[txt_files]9 để kiểm tra xem một tệp hoặc thư mục đã cho có phải là một thư mục hay không
- Nếu đó là một thư mục, hàm sẽ tự gọi đệ quy để tìm kiếm các tệp có phần mở rộng cụ thể trong thư mục đó
- Nếu là tệp, hàm sẽ kiểm tra phần mở rộng và in tên tệp ra nếu nó kết thúc bằng phần mở rộng đích
Hãy gọi hàm này để xem nó hoạt động
Ví dụ
Hãy tiếp tục với thư mục dự án Ví dụ với cấu trúc sau
. ├── Data │ └── ages.txt │ └── numbers.txt ├── Images │ └── image.png ├── Samples │ └── codes.txt │ └── readme.txt ├── finder.py ├── names.txt └── values.txt
Mục tiêu của chúng tôi là tìm tất cả các tệp
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]4 trong toàn bộ thư mục [bao gồm cả các thư mục con] bằng cách chạy tập lệnh trong tệp
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]1
Để làm điều này, hãy sao chép hàm
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]2 từ phần trước vào tệp
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]1
Hãy gọi hàm bằng cách đặt thư mục hiện tại và
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]4 làm tham số
find_files['.', '.txt']
đầu ra
./Data/numbers.txt ./Data/ages.txt ./Samples/readme.txt ./Samples/codes.txt ./names.txt ./values.txt
Đáng kinh ngạc. Lần này, chức năng không chỉ tìm thấy các tệp văn bản ở cùng cấp độ với tệp python mà còn tìm thấy các tệp văn bản trong các thư mục con
Mặc dù ví dụ này cung cấp một bài thực hành tuyệt vời với đệ quy trong Python, vẫn có một giải pháp thay thế dễ dàng hơn để tìm tệp
3. các 'os. chức năng đi bộ
Cách dễ nhất để tìm đệ quy tất cả các tệp có phần mở rộng cụ thể trong một thư mục và các thư mục con của nó là sử dụng hàm
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]2
Đây là những gì gọi nó có thể trông giống như
import os for root, dirs, files in os.walk['/path/to/directory']: for file in files: if file.endswith['.someextension']: print[os.path.join[root, file]]
Mã này nhập mô-đun
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]6, cung cấp các chức năng để tương tác với hệ điều hành. Sau đó, nó sử dụng hàm
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]7 để lặp lại đệ quy qua tất cả các thư mục và thư mục con trong thư mục đã chỉ định ['
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]8y']
Đối với mỗi thư mục trong cây, nó đặt ba biến. gốc, thư mục và tập tin. Biến
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]9 chứa đường dẫn đến thư mục hiện tại,
['names.txt', 'values.txt']0 là danh sách các thư mục con trong thư mục đó và
['names.txt', 'values.txt']1 là danh sách các tệp trong thư mục hiện tại
Sau đó, nó lặp qua danh sách các tệp trong thư mục hiện tại và kiểm tra xem mỗi tệp có kết thúc bằng phần mở rộng được chỉ định hay không. Nếu có, nó sẽ in đường dẫn đầy đủ đến tệp đó bằng hàm
['names.txt', 'values.txt']2. Điều này cho phép nó tìm tất cả các tệp có phần mở rộng được chỉ định trong toàn bộ cây thư mục, không chỉ thư mục hiện tại
Đây là một sự thay thế thuận tiện cho cách tiếp cận đệ quy khá dài từ phần trước
Ví dụ
Hãy tiếp tục với cấu trúc dự án mà bạn đã thấy trong hướng dẫn này
. ├── Data │ └── ages.txt │ └── numbers.txt ├── Images │ └── image.png ├── Samples │ └── codes.txt │ └── readme.txt ├── finder.py ├── names.txt └── values.txt
Đặc biệt, hãy tìm tất cả các. txt khỏi toàn bộ thư mục và các thư mục con của nó
Để làm điều này, hãy sửa đổi mã được giới thiệu trước đó để nhắm mục tiêu thư mục hiện tại và chỉ hiển thị các tệp có phần mở rộng
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]4
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]1
Chạy
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]1 với đoạn mã trên hiển thị tất cả các tệp có phần mở rộng
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]4
Tóm lược
Hôm nay bạn đã học cách tìm tệp có phần mở rộng cụ thể trong Python
Để về nhà, hãy sử dụng hàm
import glob # Find all files with the .txt extension in the current directory txt_files = glob.glob['*.txt'] # Print the names of the files found print[txt_files]7 để duyệt qua các thư mục và thư mục con theo cách đệ quy để tìm tất cả các tệp có phần mở rộng cụ thể