如何用Python从Azure FileShare下载文件并保留原元数据
问题描述
我需要用Python从Azure FileShare下载文件,同时保留文件的原始元数据(比如创建日期、修改日期)。但目前用FileService或ShareFileClient(azure-storage或azure-storage-file库)下载时,本地生成的新文件元数据会被修改,试过rclone这类外部工具也没能解决这个问题。
现有代码示例
# 使用文件共享和ShareFileClient下载文件 account_name = "已修改的账户名" account_key = "已修改的账户密钥" share_name = "已修改的共享名" file_name = "test.png" # 初始化ShareServiceClient service_client = ShareServiceClient(account_url=f"https://{account_name}.file.core.windows.net", credential=account_key) # 获取文件引用 file_client = service_client.get_share_client(share_name).get_directory_client(None).get_file_client(file_name) file_props = file_client.get_file_properties() file_metadata = file_props.metadata local_file_path = "./test.png"
解决方案
要保留原始元数据,需要分两步完成:先下载文件内容,再从Azure获取原始时间戳并修改本地文件的对应属性。
完整代码实现
import os import time from azure.storage.fileshare import ShareServiceClient account_name = "你的账户名" account_key = "你的账户密钥" share_name = "你的共享名" file_name = "test.png" local_file_path = "./test.png" # 初始化客户端并获取文件属性 service_client = ShareServiceClient(account_url=f"https://{account_name}.file.core.windows.net", credential=account_key) file_client = service_client.get_share_client(share_name).get_file_client(file_name) file_props = file_client.get_file_properties() # 下载文件内容到本地 with open(local_file_path, "wb") as local_file: download_stream = file_client.download_file() local_file.write(download_stream.readall()) # 提取Azure文件的原始时间戳(转成时间戳格式) creation_timestamp = file_props.creation_time.timestamp() last_modified_timestamp = file_props.last_modified.timestamp() # 根据系统类型修改本地文件的时间属性 if os.name == 'nt': # Windows系统:使用pywin32库修改创建和修改时间,需先执行pip install pywin32 import win32file import win32con file_handle = win32file.CreateFile( local_file_path, win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE, None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None ) win32file.SetFileTime(file_handle, creation_timestamp, None, last_modified_timestamp) file_handle.close() else: # Unix-like系统(Linux/macOS) # 先修改修改时间和访问时间 os.utime(local_file_path, (time.time(), last_modified_timestamp)) # macOS下额外修改创建时间(通过xattr命令) if os.uname().sysname == 'Darwin': import subprocess subprocess.run([ 'xattr', '-w', 'com.apple.metadata:kMDItemContentCreationDate', file_props.creation_time.strftime('%Y-%m-%dT%H:%M:%SZ'), local_file_path ]) # Linux的创建时间(ctime)由系统维护,无法通过常规API修改,若需修改需使用底层工具,不建议生产环境操作
关键说明
- 从
file_props中可以直接获取Azure文件的creation_time和last_modified属性,二者均为UTC时区的datetime对象,需转成时间戳后才能设置到本地文件。 - Windows系统依赖
pywin32库,需提前安装。 - Unix-like系统中创建时间的修改方式存在差异:macOS可通过扩展属性设置,Linux的创建时间通常无法直接修改,需谨慎处理。
内容的提问来源于stack exchange,提问作者Diego Buelvas
相关产品推荐
相关产品推荐

