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

如何获取HDFS中文件的名称、创建时间、修改时间等属性信息?

方案说明

首先明确:Python标准库的os模块仅能操作本地文件系统,无法直接读取HDFS的元数据,该方案不可行。以下是两种可直接落地的实现方式:

方案1:使用第三方hdfs库实现

这是Python操作HDFS的常用成熟库,实现逻辑简洁,性能稳定。

  • 第一步:安装依赖
pip install hdfs
  • 第二步:执行查询代码
import time
from hdfs import InsecureClient

# 替换为你实际的NameNode地址、端口、HDFS操作用户名
client = InsecureClient('http://<你的NameNodeIP>:50070', user='<hdfs用户名>')
# 替换为你要扫描的HDFS目标路径
target_path = '/你要查询的HDFS目录路径'

for root, dirs, files in client.walk(target_path):
    for file_name in files:
        file_full_path = f"{root}/{file_name}"
        # 获取文件全量元数据
        file_meta = client.status(file_full_path)
        # 转换时间戳为可读格式(HDFS返回时间为毫秒级时间戳)
        create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(file_meta['creationTime']/1000))
        modify_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(file_meta['modificationTime']/1000))
        access_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(file_meta['accessTime']/1000))
        # 按需输出或存储结果
        print(f"文件名:{file_name},创建日期:{create_time},修改时间:{modify_time},上次访问时间:{access_time}")

方案2:调用HDFS原生命令实现

如果不想安装第三方依赖,可直接通过Python调用HDFS客户端命令解析结果,要求运行脚本的机器已配置好HDFS客户端,可正常执行hdfs命令。

  • 核心查询命令说明:hdfs dfs -stat可直接返回文件的指定元数据,常用格式符如下:
    • %n:文件名
    • %z:文件创建时间毫秒级时间戳
    • %Y:文件修改时间毫秒级时间戳
    • %a:文件上次访问时间毫秒级时间戳
  • 示例代码:
import time
import subprocess

# 替换为你要扫描的HDFS目标路径
target_path = '/你要查询的HDFS目录路径'

# 先获取目标路径下所有文件的全路径
list_cmd = f"hdfs dfs -find {target_path} -type f"
list_result = subprocess.run(list_cmd, shell=True, capture_output=True, text=True, encoding='utf-8')
all_files = list_result.stdout.strip().split('\n')

for file_path in all_files:
    if not file_path:
        continue
    # 拉取文件元数据
    stat_cmd = f'hdfs dfs -stat "%n %z %Y %a" {file_path}'
    stat_result = subprocess.run(stat_cmd, shell=True, capture_output=True, text=True, encoding='utf-8')
    stat_info = stat_result.stdout.strip().split()
    if len(stat_info) !=4:
        continue
    file_name, create_ts, modify_ts, access_ts = stat_info
    # 转换时间格式
    create_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(create_ts)/1000))
    modify_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(modify_ts)/1000))
    access_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(access_ts)/1000))
    # 按需输出或存储结果
    print(f"文件名:{file_name},创建日期:{create_time},修改时间:{modify_time},上次访问时间:{access_time}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:45:02