You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的Folderstats获取文件夹中各文件的最后修改用户?

获取文件夹内文件最后修改用户的方法思路

folderstats本身没有提供文件最后修改用户的字段,得结合系统原生工具、文件专属库来实现,分场景整理如下:

一、系统层面的通用方案(所有文件类型兜底)

Windows系统

Windows的NTFS文件系统可以通过pywin32库读取文件的所有者信息(注意:这是文件所有者,不是最后修改操作的用户,后者需要开启文件审核才能追踪):

import win32api
import win32security

def get_win_file_owner(file_path):
    sd = win32security.GetFileSecurity(file_path, win32security.OWNER_SECURITY_INFORMATION)
    owner_sid = sd.GetSecurityDescriptorOwner()
    name, domain, _ = win32security.LookupAccountSid(None, owner_sid)
    return f"{domain}\\{name}"

# 把结果合并到你的DataFrame
df['modified_user'] = df['path'].apply(get_win_file_owner)

Linux/macOS系统

Unix-like系统可以通过os.stat获取文件的UID,再映射为用户名:

import os
import pwd

def get_unix_file_owner(file_path):
    stat_info = os.stat(file_path)
    return pwd.getpwuid(stat_info.st_uid).pw_name

# 应用到DataFrame
df['modified_user'] = df['path'].apply(get_unix_file_owner)

二、Office文件(doc/docx)的精准获取

Office文件内部的元数据会记录最后修改者,比系统层面的所有者更准确:

docx文件

用python-docx读取内置属性:

from docx import Document

def get_docx_last_modifier(file_path):
    try:
        doc = Document(file_path)
        return doc.core_properties.last_modified_by
    except Exception:
        return None

# 只对docx文件应用,覆盖兜底值
docx_rows = df['path'].str.endswith('.docx')
df.loc[docx_rows, 'modified_user'] = df.loc[docx_rows, 'path'].apply(get_docx_last_modifier)

doc文件(旧版Office)

Windows下可以用win32com.client调用Word读取:

import win32com.client

def get_doc_last_modifier(file_path):
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = False
    try:
        doc = word.Documents.Open(file_path)
        return doc.BuiltInDocumentProperties("Last author").Value
    except Exception:
        return None
    finally:
        doc.Close()
        word.Quit()

三、图片文件(jpg/png)的尝试读取

普通JPG/PNG的Exif元数据通常不会记录修改用户,只有部分专业工具生成的图片可能会写入创作者信息,用exifread尝试读取:

import exifread

def get_image_creator(file_path):
    with open(file_path, 'rb') as f:
        tags = exifread.process_file(f)
        artist_tag = tags.get('Image Artist') or tags.get('EXIF:Artist')
        return artist_tag.values if artist_tag else None

# 应用到图片文件
img_rows = df['path'].str.endswith(('.jpg', '.png'))
df.loc[img_rows, 'modified_user'] = df.loc[img_rows, 'path'].apply(get_image_creator)

四、整合建议

  1. 先运行系统层面的兜底方法,给所有文件填充所有者信息。
  2. 再针对Office文件用专属方法覆盖结果,因为这类文件的内部元数据更符合"最后修改用户"的需求。
  3. 图片文件尝试读取后,没有结果的保留兜底值或标记为「未知」。

内容的提问来源于stack exchange,提问作者Captain Somma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 15:40:09