通过python代码进行操作HDFS

1 通过在hadoop节点上自带命令操作HDFS

比如我们用下面命令

查看/test目录
hdfs dfs -ls /test
查看目录或者文件的块信息
hdfs fsck / -files -blocks -locations -racks
hdfs fsck /test/start.txt -files -blocks -locations -racks
修改目录权限
hdfs dfs -chmod -R 777 /test

2 通过代码远程操作HDFS,目前用python进出实验

使用python3.6对hdfs库进行操作

安装依赖:

pip3 install --upgrade pip #更新pip,防止版本过低

pip3 install pyHdfs #安装pyHdfs

编码:

from pyhdfs import HdfsClient

if __name__ == '__main__':
client = HdfsClient(hosts='hadoop2.com:50070') # 50070是端口号
print(client.list_status('/')) # 打印
print(client.list_status('/test')) # 打印
print(client.copy_to_local('/test/start.txt','start2.txt')) # 从hadoop集群中下载文件
print(client.mkdirs('/test/python', permission=777)) #在hadoop集群中创建目录
print(client.copy_from_local('start2.txt', '/test/python/start2.txt')) #把本地文件上传hadoop集群
print(client.delete('/test/python/start2.txt')) #删除hadoop集群文件
print(client.delete('/test/python')) #删除hadoop集群目录

  

原文地址:https://www.cnblogs.com/kuainiao/p/9395705.html