使用 hdfs 库中的 InsecureClient 操作 HDFS,需先安装依赖:pip install hdfs。以下实例涵盖连接、上传、下载、查看(列表/状态/内容)及删除操作 。‌‌

1. 初始化客户端

from hdfs import InsecureClient 
# 替换为你的 NameNode WebHDFS 地址和端口(Hadoop 2.x/3.x 常见为 50070 或 9870) 
client = InsecureClient('http://localhost:9870', user='root')

2. 上传文件

将本地文件上传至 HDFS,支持自动覆盖。

local_path = '/path/to/local/file.txt' 
hdfs_path = '/user/root/hdfs_file.txt' 
# 参数 overwrite=True 表示若文件存在则覆盖 
client.upload(hdfs_path, local_path, overwrite=True)

3. 下载文件

将 HDFS 文件下载到本地指定目录或路径。

hdfs_path = '/user/root/hdfs_file.txt' 
local_path = '/path/to/local/downloaded_file.txt' 
# n_threads 可设置多线程加速下载 
client.download(hdfs_path, local_path, n_threads=1)

4. 查看文件与目录

提供三种查看方式:列出目录、获取文件元数据、读取文件内容。

  • 列出目录内容
files = client.list('/user/root/') 
for name, status in files: 
    print(f"名称: {name}, 类型: {status['type']}")
  • 获取文件状态(元数据)
 try: 
    status = client.status('/user/root/hdfs_file.txt') 
    print(f"文件大小: {status['length']} 字节, 权限: {status['permission']}") 
except Exception: 
    print("文件不存在")
  • 读取文件内容
with client.read('/user/root/hdfs_file.txt', encoding='utf-8') as reader: 
    content = reader.read() 
    print(content)

5. 删除文件或删除目录

删除操作不可逆,删除目录需开启递归模式。

# 删除单个文件 
client.delete('/user/root/hdfs_file.txt') 
# 删除目录及其所有内容 
client.delete('/user/root/old_folder', recursive=True)

注意事项

  • 端口差异‌:Hadoop 2.x 默认 WebHDFS 端口为 50070,Hadoop 3.x 通常为 9870,请根据集群配置调整 URL 。
  • 路径检查‌:使用 status(path, strict=False) 可避免路径不存在时报错,返回 None 而非异常 。
  • 安全性‌:InsecureClient 无 Kerberos 认证,仅适用于测试或内网可信环境,生产环境建议使用 KerberosClient 。‌‌

更多推荐