Hướng dẫn how do you find all .txt file in any directory python? - làm cách nào để bạn tìm thấy tất cả tệp .txt trong bất kỳ thư mục nào python?

Python v3.5+

Phương pháp nhanh bằng cách sử dụng OS.Scandir trong một hàm đệ quy. Tìm kiếm tất cả các tệp với một tiện ích mở rộng được chỉ định trong thư mục và trình phụ phụ. Nó là nhanh, ngay cả khi tìm thấy 10.000 tệp.

Tôi cũng đã bao gồm một chức năng để chuyển đổi đầu ra thành khung dữ liệu gấu trúc.

import os
import re
import pandas as pd
import numpy as np


def findFilesInFolderYield(path,  extension, containsTxt='', subFolders = True, excludeText = ''):
    """  Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:               Base directory to find files
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """
    if type(containsTxt) == str: # if a string and not in a list
        containsTxt = [containsTxt]
    
    myregexobj = re.compile('\.' + extension + '$')    # Makes sure the file extension is at the end and is preceded by a .
    
    try:   # Trapping a OSError or FileNotFoundError:  File permissions problem I believe
        for entry in os.scandir(path):
            if entry.is_file() and myregexobj.search(entry.path): # 
    
                bools = [True for txt in containsTxt if txt in entry.path and (excludeText == '' or excludeText not in entry.path)]
    
                if len(bools)== len(containsTxt):
                    yield entry.stat().st_size, entry.stat().st_atime_ns, entry.stat().st_mtime_ns, entry.stat().st_ctime_ns, entry.path
    
            elif entry.is_dir() and subFolders:   # if its a directory, then repeat process as a nested function
                yield from findFilesInFolderYield(entry.path,  extension, containsTxt, subFolders)
    except OSError as ose:
        print('Cannot access ' + path +'. Probably a permissions error ', ose)
    except FileNotFoundError as fnf:
        print(path +' not found ', fnf)

def findFilesInFolderYieldandGetDf(path,  extension, containsTxt, subFolders = True, excludeText = ''):
    """  Converts returned data from findFilesInFolderYield and creates and Pandas Dataframe.
    Recursive function to find all files of an extension type in a folder (and optionally in all subfolders too)

    path:               Base directory to find files
    extension:          File extension to find.  e.g. 'txt'.  Regular expression. Or  'ls\d' to match ls1, ls2, ls3 etc
    containsTxt:        List of Strings, only finds file if it contains this text.  Ignore if '' (or blank)
    subFolders:         Bool.  If True, find files in all subfolders under path. If False, only searches files in the specified folder
    excludeText:        Text string.  Ignore if ''. Will exclude if text string is in path.
    """
    
    fileSizes, accessTimes, modificationTimes, creationTimes , paths  = zip(*findFilesInFolderYield(path,  extension, containsTxt, subFolders))
    df = pd.DataFrame({
            'FLS_File_Size':fileSizes,
            'FLS_File_Access_Date':accessTimes,
            'FLS_File_Modification_Date':np.array(modificationTimes).astype('timedelta64[ns]'),
            'FLS_File_Creation_Date':creationTimes,
            'FLS_File_PathName':paths,
                  })
    
    df['FLS_File_Modification_Date'] = pd.to_datetime(df['FLS_File_Modification_Date'],infer_datetime_format=True)
    df['FLS_File_Creation_Date'] = pd.to_datetime(df['FLS_File_Creation_Date'],infer_datetime_format=True)
    df['FLS_File_Access_Date'] = pd.to_datetime(df['FLS_File_Access_Date'],infer_datetime_format=True)

    return df

ext =   'txt'  # regular expression 
containsTxt=[]
path = 'C:\myFolder'
df = findFilesInFolderYieldandGetDf(path,  ext, containsTxt, subFolders = True)

Cần liệt kê tất cả các tệp văn bản trong một thư mục bằng Python?

Nếu vậy, bạn có thể sử dụng các mẫu sau để liệt kê các tệp của mình:

Liệt kê tất cả các tệp văn bản trong một thư mục:

import glob
import os

os.chdir(r'directory where the files are located')
my_files = glob.glob('*.txt')
print(my_files)

Liệt kê các đường dẫn của các tệp văn bản:

import glob

my_files_path = glob.glob(r'directory where the files are located\*.txt')
print(my_files_path)

Trong phần tiếp theo, bạn sẽ thấy một ví dụ với các bước để liệt kê tất cả các tệp văn bản bằng Python.

Bước 1: Xác định vị trí thư mục chứa các tệp văn bản

Ví dụ: hãy giả sử rằng 2 tệp văn bản sau đây được lưu trữ trong một thư mục có tên là Test:

Sản phẩm mới sản phẩm cũ
Old Products

Bước 2: Chụp đường dẫn nơi lưu trữ các tệp văn bản

Tiếp theo, chụp đường dẫn của thư mục nơi lưu trữ các tệp văn bản.

Ví dụ của chúng tôi, đường dẫn lưu trữ 2 tệp như sau:

C: \ Users \ ron \ Desktop \ test

Bạn cần phải sửa đổi đường dẫn để phản ánh vị trí lưu trữ các tệp văn bản trên máy tính của bạn.

Bước 3: Liệt kê tất cả các tệp văn bản trong thư mục bằng Python

Để liệt kê tất cả các tệp văn bản trong một thư mục bằng Python, bạn sẽ cần nhập các gói HĐH và HĐH.

Sau đó, bạn có thể sử dụng mẫu sau để liệt kê các tệp văn bản của mình:

import glob
import os

os.chdir(r'directory where the files are located')
my_files = glob.glob('*.txt')
print(my_files)

Và ví dụ của chúng tôi, đây là mã Python hoàn chỉnh để liệt kê các tệp văn bản:

import glob
import os

os.chdir(r'C:\Users\Ron\Desktop\Test')
my_files = glob.glob('*.txt')
print(my_files)

Chạy mã (được điều chỉnh theo đường dẫn của bạn) và bạn sẽ thấy danh sách các tệp văn bản:

['New Products.txt', 'Old Products.txt']

Don Tiết quên đặt ra R Rv trước con đường để tránh lỗi sau trong Python:

.

Bước tùy chọn: Liệt kê các đường dẫn của các tệp văn bản

Điều gì sẽ xảy ra nếu bạn muốn có được một danh sách các đường dẫn của các tệp văn bản của bạn?

Nếu trường hợp đó, bạn có thể sử dụng mẫu sau:

import glob

my_files_path = glob.glob(r'directory where the files are located\*.txt')
print(my_files_path)

Và ví dụ của chúng tôi:

import glob

my_files_path = glob.glob(r'C:\Users\Ron\Desktop\Test\*.txt')
print(my_files_path)

Đây là những con đường cho ví dụ của chúng tôi:

['C:\\Users\\Ron\\Desktop\\Test\\New Products.txt', 
'C:\\Users\\Ron\\Desktop\\Test\\Old Products.txt']