使用python将指定文件夹下的全部文件上传到 hdfs 的指定路径

     因在公司业务上遇到一个需求,需要将指定服务器上的指定路径下的所有文件,例如:test.csv 上传到hdfs上,参考了网上的一些大佬的帖子实现了需求,故做个笔记方便以后查看,参考地址:https://www.cnblogs.com/SmallCaff/p/10650699.html

import os
import platform
import logging as lg
from hdfs.client import Client
from hdfs.client import _logger

'''
使用前需先安装
pip install hdfs 
'''
#setting配置部分
HOST = "http://192.168.12.101:50070"  # 地址
ROOT_PATH = "/"  # 客户端连接的目录
REMOTE_PATH = "/air_test_data"  # HDFS上的路径,注意,需要先在hdfs手动创建此目录
LOCAL_PATH = "file/excel_file"  # 本地路径,建议写绝对路径,例如:E:\my_work\测试目录
LOG_DIR = "log/upload.log"  # 日志路径 建议写绝对路径,例如:E:\my_work\log

#-------------------------------------------------------
# 记录日志(用了hdfs中源码的logger)
logdir = LOG_DIR
_logger.setLevel(lg.DEBUG)
myhandler = lg.FileHandler(logdir, "w")  # 覆盖模式输出日志
myhandler.setLevel(lg.DEBUG)
formatter = lg.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
myhandler.setFormatter(formatter)
_logger.addHandler(myhandler)


class Transfer(object):

    def __init__(self):
        self.host = HOST
        self.remotepath = REMOTE_PATH
        self.localpath = LOCAL_PATH
        self.rootpath = ROOT_PATH
        self.client = Client(self.host, root=self.rootpath)

    def upload_file_windows(self):
        """windowsserver"""
        try:
            base_dir = self.localpath.split('\\').pop()  # 要上传的路径的最后一个文件夹

            for root, dirs, files in os.walk(self.localpath):

                new_dir = base_dir + root.split(base_dir).pop().replace('\\','/')  # 去除本地路径前缀


                for file in files:
                    old_path = root + '\\' + file  # 原始本地路径文件
                    lpath = new_dir + '/' + file  # 去除本地路径前缀后的文件

                    if not self.client.status(self.remotepath + '/' + lpath, strict=False):

                        # 第一个参数远程路径,第二个参数本地路径,第三个参数是否覆盖,第四个参数工作线程数
                        self.client.upload(self.remotepath + '/' + lpath, old_path, overwrite=False)

        except Exception as e:
            with open("err.log", "a") as f:
                f.write(str(e))

    def upload_file_linux(self, sep):
        """linuxserver"""
        try:
            base_dir = self.localpath.split(sep).pop()  # 要上传的路径的最后一个文件夹

            for root, dirs, files in os.walk(self.localpath):

                new_dir = base_dir + root.split(base_dir).pop()  # 去除本地路径前缀

                for file in files:
                    old_path = root + sep + file  # 原始本地路径文件
                    lpath = new_dir + sep + file  # 去除本地路径前缀后的文件

                    if not self.client.status(self.remotepath + sep + lpath, strict=False):
                        # len(old_path.split("/"))
                        # 第一个参数远程路径,第二个参数本地路径,第三个参数是否覆盖,第四个参数工作线程数
                        self.client.upload(self.remotepath + sep + lpath, old_path, overwrite=False)
        except Exception as e:
            with open("err.log", "a") as f:
                f.write(str(e))


if __name__ == "__main__":
    transfer = Transfer()
    # windows server
    if platform.platform().startswith("Windows"):
        transfer.upload_file_windows()
    else:
        # linux server
        transfer.upload_file_linux('/')

上传效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值