Python 操作大数据使用 Hadoop

参考:https://blog.csdn.net/wuShiJingZuo/article/details/135620018

python 复制代码
from hdfs import InsecureClient
hdfs_client = InsecureClient("http://localhost:9000", user="xiaokkk")
# 测试连接
print(hdfs_client.status("/"))
复制代码
{'accessTime': 0, 'blockSize': 0, 'childrenNum': 9, 'fileId': 16385, 'group': 'supergroup', 'length': 0, 'modificationTime': 1725326811876, 'owner': 'xiaokkk', 'pathSuffix': '', 'permission': '755', 'replication': 0, 'snapshotEnabled': True, 'storagePolicy': 0, 'type': 'DIRECTORY'}
python 复制代码
# 查看目录
files_and_dirs = hdfs_client.list("/")
print(files_and_dirs)
复制代码
['apps', 'backup', 'data', 'ks', 'logs', 'tmp', 'user']
python 复制代码
# 上传本地文件到HDFS
local_file_path = "/Users/xiaokkk/Desktop/local_projects/hadoop/input.txt"
hdfs_file_path = "/data/input.txt"

hdfs_client.upload(hdfs_file_path, local_file_path)
print(f"File {local_file_path} uploaded to {hdfs_file_path}")
复制代码
File /Users/xiaokkk/Desktop/local_projects/hadoop/input.txt uploaded to /data/input.txt
python 复制代码
# 下载HDFS文件到本地
hdfs_client.download(hdfs_file_path, "/Users/xiaokkk/Desktop/local_projects/hadoop/test_download.txt")
python 复制代码
# 删除HDFS文件
client.delete('/path/to/your/file', recursive=False)  # 如果文件是一个目录并且包含文件,则需要设置
python 复制代码
# 连接到HDFS
from hdfs import InsecureClient
client = InsecureClient("http://localhost:9000", user="xiaokkk")
# 指定HDFS上的文件路径
hdfs_path = '/data/input.txt'
# 打开HDFS上的文件
with client.read(hdfs_path, encoding='utf-8') as reader:
    # 读取文件内容
    content = reader.read()
    print(content)

# # 对文件内容进行处理,例如统计行数
# line_count = content.count('\n')
# print(f"文件 {hdfs_path} 包含 {line_count + 1} 行")
# 
# # 如果你想处理每一行,可以这样做
# for line in content.splitlines():
#     # 处理每一行
#     print(line)
复制代码
Hello world, this is a simple example of a text file.
This file will be used to demonstrate how the word count works.
Every word will be counted, and thpython word_count.py input.txt another_input.txt > output.txte results will show the frequency of each word.
相关推荐
Lx3521 小时前
Hadoop小文件处理难题:合并与优化的最佳实践
大数据·hadoop
最初的↘那颗心16 小时前
Flink Stream API 源码走读 - print()
java·大数据·hadoop·flink·实时计算
君不见,青丝成雪17 小时前
hadoop技术栈(九)Hbase替代方案
大数据·hadoop·hbase
晴天彩虹雨17 小时前
存算分离与云原生:数据平台的新基石
大数据·hadoop·云原生·spark
最初的↘那颗心1 天前
Flink Stream API - 源码开发需求描述
java·大数据·hadoop·flink·实时计算
Lx3521 天前
MapReduce作业调试技巧:从本地测试到集群运行
大数据·hadoop
BYSJMG1 天前
计算机大数据毕业设计推荐:基于Spark的气候疾病传播可视化分析系统【Hadoop、python、spark】
大数据·hadoop·python·信息可视化·spark·django·课程设计
励志成为糕手1 天前
大数据MapReduce架构:分布式计算的经典范式
大数据·hadoop·mapreduce·分布式计算·批处理
计算机毕设-小月哥1 天前
大数据毕业设计选题推荐:基于Hadoop+Spark的城镇居民食品消费分析系统源码
大数据·hadoop·课程设计
Viking_bird2 天前
centos 7.5 + Hadoop 3.2.4 集群搭建
linux·运维·服务器·hadoop·centos