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.pyTệ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 pdSau đó 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 sizeTrong 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. 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à. 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.Tạo danh sách các tệp trong thư mục và thư mục phụ bằng os.listdir ()
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à.
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à.
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,
Ví dụ hoàn chỉnh như sau,
f-rwxrwxrwx,1,cathy,cathy,2642,2021-06-01+00:22:00.2970880000,content-audit.py 0Output:
f-rwxrwxrwx,1,cathy,cathy,2642,2021-06-01+00:22:00.2970880000,content-audit.py 1 & nbsp;Quảng cáo