Hướng dẫn list all file in subdirectories python - liệt kê tất cả các tệp trong thư mục con python

Giải pháp khá đơn giản sẽ là chạy một vài cuộc gọi quy trình phụ để xuất các tệp vào định dạng CSV:

import subprocess

# Global variables for directory being mapped

location = '.' # Enter the path here.
pattern = '*.py' # Use this if you want to only return certain filetypes
rootDir = location.rpartition('/')[-1]
outputFile = rootDir + '_directory_contents.csv'

# Find the requested data and export to CSV, specifying a pattern if needed.
find_cmd = 'find ' + location + ' -name ' + pattern +  ' -fprintf ' + outputFile + '  "%Y%M,%n,%u,%g,%s,%A+,%P\n"'
subprocess.call(find_cmd, shell=True)

Lệnh đó tạo ra các giá trị phân tách bằng dấu phẩy có thể dễ dàng phân tích trong Excel.

f-rwxrwxrwx,1,cathy,cathy,2642,2021-06-01+00:22:00.2970880000,content-audit.py

Tệp CSV kết quả không có hàng tiêu đề, nhưng bạn có thể sử dụng lệnh thứ hai để thêm chúng.

# Add headers to the CSV
headers_cmd = 'sed -i.bak 1i"Permissions,Links,Owner,Group,Size,ModifiedTime,FilePath" ' + outputFile
subprocess.call(headers_cmd, shell=True)

Tùy thuộc vào lượng dữ liệu bạn nhận lại, bạn có thể xoa bóp nó thêm bằng gấu trúc. Dưới đây là một số điều tôi thấy hữu ích, đặc biệt nếu bạn đang xử lý nhiều cấp độ thư mục để xem qua.

Thêm những thứ này vào nhập khẩu của bạn:

import numpy as np
import pandas as pd

Sau đó thêm cái này vào mã của bạn:

# Create DataFrame from the csv file created above.
df = pd.read_csv(outputFile)
    
# Format columns
# Get the filename and file extension from the filepath 
df['FileName'] = df['FilePath'].str.rsplit("/",1).str[-1]
df['FileExt'] = df['FileName'].str.rsplit('.',1).str[1]

# Get the full path to the files. If the path doesn't include a "/" it's the root directory
df['FullPath'] = df["FilePath"].str.rsplit("/",1).str[0]
df['FullPath'] = np.where(df['FullPath'].str.contains("/"), df['FullPath'], rootDir)

# Split the path into columns for the parent directory and its children
df['ParentDir'] = df['FullPath'].str.split("/",1).str[0]
df['SubDirs'] = df['FullPath'].str.split("/",1).str[1]
# Account for NaN returns, indicates the path is the root directory
df['SubDirs'] = np.where(df.SubDirs.str.contains('NaN'), '', df.SubDirs)

# Determine if the item is a directory or file.
df['Type'] = np.where(df['Permissions'].str.startswith('d'), 'Dir', 'File')

# Split the time stamp into date and time columns
df[['ModifiedDate', 'Time']] = df.ModifiedTime.str.rsplit('+', 1, expand=True)
df['Time'] = df['Time'].str.split('.').str[0]

# Show only files, output includes paths so you don't necessarily need to display the individual directories.
df = df[df['Type'].str.contains('File')]

# Set columns to show and their order.
df=df[['FileName','ParentDir','SubDirs','FullPath','DocType','ModifiedDate','Time', 'Size']]

filesize=[] # Create an empty list to store file sizes to convert them to something more readable.

# Go through the items and convert the filesize from bytes to something more readable.
for items in df['Size'].items():
    filesize.append(convert_bytes(items[1]))
    df['Size'] = filesize 

# Send the data to an Excel workbook with sheets by parent directory
with pd.ExcelWriter("scripts_directory_contents.xlsx") as writer:
    for directory, data in df.groupby('ParentDir'):
    data.to_excel(writer, sheet_name = directory, index=False) 
        

# To convert sizes to be more human readable
def convert_bytes(size):
    for x in ['b', 'K', 'M', 'G', 'T']:
        if size < 1024:
            return "%3.1f %s" % (size, x)
        size /= 1024

    return size

Trong bài viết này, chúng tôi sẽ thảo luận về các phương pháp khác nhau để tạo danh sách tất cả các tệp trong cây thư mục.

Tạo danh sách các tệp trong thư mục và thư mục phụ bằng os.listdir ()

Mô -đun HĐH Python cung cấp một chức năng để có được danh sách các tệp hoặc thư mục trong một thư mục, tức là.

os.listdir(path='.')

Nó trả về một danh sách tất cả các tệp và thư mục phụ trong đường dẫn đã cho.

Chúng ta cần gọi đây là đệ quy cho các thư mục phụ để tạo một danh sách đầy đủ các tệp trong cây thư mục đã cho, tức là.

'''
    For the given path, get the List of all files in the directory tree 
'''
def getListOfFiles(dirName):
    # create a list of file and sub directories 
    # names in the given directory 
    listOfFile = os.listdir(dirName)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory 
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(fullPath)
                
    return allFiles

Gọi hàm trên để tạo danh sách các tệp trong cây thư mục, tức là.

dirName = '/home/varun/Downloads';

# Get the list of all files in directory tree at given path
listOfFiles = getListOfFiles(dirName)

Tạo danh sách các tệp trong thư mục và thư mục phụ bằng Os.Walk ()

Mô -đun HĐH Python cung cấp một chức năng để lặp lại trên cây thư mục, tức là.

os.walk(path)

Nó lặp lại của cây thư mục tại đường dẫn cho mỗi thư mục hoặc thư mục phụ, nó trả về một tuple chứa, (,,.
(

, , .
Iterate over the directory tree and generate a list of all the files at given path,

# Get the list of all files in directory tree at given path
listOfFiles = list()
for (dirpath, dirnames, filenames) in os.walk(dirName):
    listOfFiles += [os.path.join(dirpath, file) for file in filenames]

Ví dụ hoàn chỉnh như sau,

f-rwxrwxrwx,1,cathy,cathy,2642,2021-06-01+00:22:00.2970880000,content-audit.py
0

Output:

f-rwxrwxrwx,1,cathy,cathy,2642,2021-06-01+00:22:00.2970880000,content-audit.py
1 & nbsp;

Quảng cáo

Làm cách nào để liệt kê các tệp trong một thư mục con 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 .

Làm cách nào để có được một danh sách các tệp trong thư mục và thư mục con?

Lệnh LS được sử dụng để liệt kê các tệp hoặc thư mục trong Linux và các hệ điều hành dựa trên UNIX khác. Giống như bạn điều hướng trong trình thám hiểm tệp hoặc trình tìm kiếm của bạn với GUI, lệnh LS cho phép bạn liệt kê tất cả các tệp hoặc thư mục trong thư mục hiện tại theo mặc định và tương tác thêm với chúng thông qua dòng lệnh. is used to list files or directories in Linux and other Unix-based operating systems. Just like you navigate in your File explorer or Finder with a GUI, the ls command allows you to list all files or directories in the current directory by default, and further interact with them via the command line.

Làm cách nào để liệt kê tất cả các tệp trong một thư mục đệ quy?

Hãy thử bất kỳ một trong các lệnh sau để xem danh sách thư mục đệ quy: LS -R: Sử dụng lệnh LS để nhận danh sách thư mục đệ quy trên Linux.Tìm / DIR / -Print: Chạy lệnh Tìm để xem danh sách thư mục đệ quy trong Linux.du -A.: Thực hiện lệnh DU để xem danh sách thư mục đệ quy trên UNIX.ls -R : Use the ls command to get recursive directory listing on Linux. find /dir/ -print : Run the find command to see recursive directory listing in Linux. du -a . : Execute the du command to view recursive directory listing on Unix.

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

Đây là các bước ...
Nhập mô -đun hệ điều hành.Mô -đun OS cung cấp nhiều chức năng để tương tác với hệ điều hành.....
Tạo một biến bộ đếm.Đặt bộ đếm thành 0.....
Sử dụng hàm Os.ListDir ().Hệ điều hành.....
Lặp lại kết quả.....
Sử dụng hàm isfile () và bộ đếm tăng thêm 1 ..