如何使用Python的os模块读取目录中文件的作者/创建者属性?
Hey there! The os module is perfect for grabbing basic file metadata like modification time, but it doesn’t have native support for fetching author or creator info—because that data is tied to platform-specific file system metadata, which works differently on Windows, macOS, and Linux. Let’s break down how to handle each case, plus a bonus tip for Office files like your customer details.xlsx:
First, Fix Your Modification Time Code Quick
Before diving into authors, a small correction: you can’t use / to concatenate paths across all platforms. Use os.path.join() instead to make your code cross-platform:
import os from datetime import datetime PATH = "my folder/books" file_name = "customer details.xlsx" full_file_path = os.path.join(PATH, file_name) # Get and format modification time mod_timestamp = os.path.getmtime(full_file_path) readable_mod_time = datetime.fromtimestamp(mod_timestamp).strftime("%Y-%m-%d %H:%M:%S") print(f"Modified: {readable_mod_time}")
Fetching Author/Creator Info by Platform
Windows
On Windows, you can use the pywin32 library to access the file’s shell properties (where author info is stored). First install it:
pip install pywin32
Then use this function:
import win32com.client def get_windows_file_author(file_path): shell = win32com.client.Dispatch("Shell.Application") folder = shell.NameSpace(os.path.dirname(file_path)) file_item = folder.ParseName(os.path.basename(file_path)) # Property index 20 corresponds to "Author" in Windows shell properties author = folder.GetDetailsOf(file_item, 20) return author if author else "Unknown Author"
macOS
macOS stores file metadata in extended attributes. You can use the mdls command via subprocess (no extra installs needed) to pull this info:
import subprocess def get_macos_file_author(file_path): # First try to get the creator creator_result = subprocess.run( ["mdls", "-name", "kMDItemCreator", file_path], capture_output=True, text=True, check=True ) creator = creator_result.stdout.strip().split("=")[-1].strip().strip('"') if creator: return creator # If no creator, try authors authors_result = subprocess.run( ["mdls", "-name", "kMDItemAuthors", file_path], capture_output=True, text=True, check=True ) authors_str = authors_result.stdout.strip().split("=")[-1].strip() if authors_str not in ("()", "[]"): import ast authors_list = ast.literal_eval(authors_str) return authors_list[0] if authors_list else "Unknown Author" return "Unknown Author"
Linux
Linux file systems don’t have a built-in "author" field, but you can get the file’s owner (the user who created or owns the file) using os.stat and pwd:
import pwd def get_linux_file_owner(file_path): stat_info = os.stat(file_path) try: return pwd.getpwuid(stat_info.st_uid).pw_name except: return f"UID: {stat_info.st_uid}"
Bonus: Directly Read Author from Excel Files
For your customer details.xlsx, the most reliable way to get the author is to read the metadata stored inside the Excel file itself (not the OS file system). Use openpyxl:
pip install openpyxl
Then:
from openpyxl import load_workbook def get_xlsx_author(file_path): wb = load_workbook(file_path, read_only=True) return wb.properties.creator if wb.properties.creator else "Unknown Author"
This works regardless of the OS, since it reads the author info embedded directly in the Excel file.
Putting It All Together
Here’s how to combine everything into a cross-platform script:
import os from datetime import datetime import sys PATH = "my folder/books" file_name = "customer details.xlsx" full_file_path = os.path.join(PATH, file_name) # Print modification time mod_timestamp = os.path.getmtime(full_file_path) readable_mod_time = datetime.fromtimestamp(mod_timestamp).strftime("%Y-%m-%d %H:%M:%S") print(f"File Modification Time: {readable_mod_time}") # Get author based on platform or file type try: # First try Excel-specific method if it's an xlsx file if file_name.endswith(".xlsx"): from openpyxl import load_workbook wb = load_workbook(full_file_path, read_only=True) author = wb.properties.creator or "Unknown Author" else: if sys.platform.startswith("win32"): import win32com.client shell = win32com.client.Dispatch("Shell.Application") folder = shell.NameSpace(os.path.dirname(full_file_path)) file_item = folder.ParseName(os.path.basename(full_file_path)) author = folder.GetDetailsOf(file_item, 20) or "Unknown Author" elif sys.platform.startswith("darwin"): import subprocess creator_result = subprocess.run( ["mdls", "-name", "kMDItemCreator", full_file_path], capture_output=True, text=True, check=True ) author = creator_result.stdout.strip().split("=")[-1].strip().strip('"') or "Unknown Author" elif sys.platform.startswith("linux"): import pwd stat_info = os.stat(full_file_path) author = pwd.getpwuid(stat_info.st_uid).pw_name or f"UID: {stat_info.st_uid}" else: author = "Unsupported Platform" print(f"File Author/Creator: {author}") except Exception as e: print(f"Error fetching author info: {str(e)}")
内容的提问来源于stack exchange,提问作者jatin grover

