Python 操作HDFS模块
python HDFS模块
安装:pip install hdfs
 介绍:该模块用于python与HDFS的namenode建立链接从而获取到datanode进行操作
 链接方式:webHDFS
实例化客户端
from hdfs import InsecureClient
 client = InsecureClient(‘http://host:port’, user=‘ann’)
insecureClient 可以添加用户参数、或者安全认证
from hdfs import Config
 client = Config().get_client(‘dev’)
读写文件
读取文件至内存
with client.read(‘features’) as reader:
 features = reader.read()
结合以下write() 方法将文件写入HDFS
client.write(‘data/records.jsonl’, data=features, encoding=‘utf-8’)
相关参数:
 write(hdfs_path,data = None,overwrite = False,permission= None,blocksize = None,replication= None,buffersize = None,append = False,encoding = None )
[hdfs_path]:写入路径,没有会自动创建
 [data]:本地数据,可以为变量
 [overwrite]:是否允许覆盖
 [permission]:权限
 [blocksize]:文件大小
 [replication]:文件复制数量
 [buffersize]:上传区域大小,类似缓冲区
 [append]:附加到文件而不是创建一个新文件。
 [encoding]:用于对写入的数据进行序列化的编码。
Kerberos认证访问
client = KerberosClient(‘http://host:port’)
列出目录
list(hdfs_path, status=False)
 [status]:返回每个文件的对应FileStatus。
创建目录(如要写入,建议使用write方法,没有会自动创建)
makedirs(hdfs_path, permission=None)
删除
delete(hdfs_path, recursive=False, skip_trash=True)
 [recursive]:默认情况下,如果尝试刪除非空目录,此方法将引发hdfs error。
 [skip_trash]:跳过垃圾回收
检查文件是否存在
checksum(hdfs_path )
必须指向一个文件
获取HDFS上文件或者目录(可用于判断是否存在)
content(hdfs_path,strict = True )
 [strict]:如果为False,则返回,None而不是在路径不存在的情況下引发异常。
移动文件或文件夹
rename(hdfs_src_path,hdfs_dst_path )
 [hdfs_src_path]:源路径
 [hdfs_dst_path]:目标路径,存在移入,不存在引发hfds error异常
参考文献
[HDFS官方API文档]:https://hdfscli.readthedocs.io/en/latest/






