当前位置: 首页 > news >正文

大数据-玩转数据-Python Sftp Mysql 数据

一、需求描述

1、从Mysql数据库表下载数据到服务器;
2、将数据已csv文件格式存储并对数据格式进行处理(添加表头,表头和数据均用竖线分隔符隔开,末尾也加分割符);
3、文件路径文件夹以天为单位,文件名中含日期和序号,序号记录相同文件在同一天重新下载传送的批次;
3、将文件压缩成.gz格式;
4、文件以Sftp方式传送到对方服务器固定位置。

二、Python 全代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paramiko,csv
import os, sys, stat
import pymysql
import time, gzipdef create_dir(sftp, sftpRemoteDir):try:if stat.S_ISDIR(sftp.stat(sftpRemoteDir).st_mode):passexcept Exception as e:sftp.mkdir(sftpRemoteDir)def sftp_upload(sftp, sftpLocalDir, sftpRemoteDir):if os.path.isdir(sftpLocalDir):for file in os.listdir(sftpLocalDir):remoteDirTmp = os.path.join(sftpRemoteDir, file)localDirTmp = os.path.join(sftpLocalDir, file)if os.path.isdir(localDirTmp):create_dir(sftp, remoteDirTmp)sftp_upload(sftp, localDirTmp, remoteDirTmp)else:print("upload file:", sftpLocalDir)try:sftp.put(sftpLocalDir, sftpRemoteDir)except Exception as e:print('upload error:', e)if __name__ == '__main__':# 变量date = time.strftime("%Y%m%d", time.localtime())sftpHost = '192.168.220.104'sftpPort = 22sftpUser = 'sftpsun'sftpPassord = 'hadoophadoop'sftpLocalDir = '/home/hadoop/python_file/' + datesftpRemoteDir = '/upload'xhDir = '/home/hadoop/xh/' + datexhFile = xhDir + '/' + 'xhFile.txt'# 序号if os.path.isdir(xhDir):if os.path.isfile(xhFile):with open(xhFile, 'r', encoding='utf-8') as f:xh = f.readline()xh = int(xh) + 1xh = str(xh).zfill(2)with open(xhFile, 'w', encoding='utf-8') as f:f.write(xh)else:with open(xhFile, 'w', encoding='utf-8') as f:f.write('00')else:os.makedirs(xhDir)with open(xhFile, 'w', encoding='utf-8') as f:f.write('00')with open(xhFile, 'r', encoding='utf-8') as f:xh = f.readline()sendFile = 'ZXSEND_0112_082_' + date + '_' + xh + '_001'sftpLocalFile = sftpLocalDir + '/' + sendFile# 目录创建if os.path.isdir(sftpLocalDir):passelse:os.makedirs(sftpLocalDir)# 数据下载conn = pymysql.connect(host="hadoop100",port=3306,user='root',password='Mysql123456#',database='flink_sql',charset='utf8')cursor = conn.cursor()sql = "select t.* from hot_item t"cursor.execute(sql)data = cursor.fetchall()print(data)cursor.close()# 数据格式处理写入本地文件header = ('w_end', 'item_id', 'item_count', 'rk')with open(sftpLocalFile + '.csv', "w+", newline="", encoding='utf-8') as f:lines = csv.writer(f,delimiter="|")lines.writerow(header)for line in data:a = list(line)lines.writerow(line)f2 = open(sftpLocalFile + '.dat', 'w',encoding='utf-8')with open(sftpLocalFile + '.csv', 'r') as f:for line in f:line = line.strip()if not line.endswith(r'|'):line += r'|'line += '\n'f2.write(line)f2.close()os.remove(sftpLocalFile + '.csv')# 压缩with open(sftpLocalFile + '.dat', 'rb') as f:data = f.read()with gzip.open(sftpLocalFile + '.dat' + '.gz', 'wb') as f:f.write(data)os.remove(sftpLocalFile + '.dat')# 文件上传sf = paramiko.Transport((sftpHost, sftpPort))sf.connect(username=sftpUser, password=sftpPassord)sftp = paramiko.SFTPClient.from_transport(sf)sftp_upload(sftp, sftpLocalDir, sftpRemoteDir)sf.close()
http://www.lryc.cn/news/211553.html

相关文章:

  • Selenium3-当元素通过@FindBy获取时,返回元素为null
  • JWT详解解读读
  • 一文详解如何从 Oracle 迁移数据到 DolphinDB
  • 负载均衡--Haproxy
  • 股票价格预测 | 融合CNN和Transformer以提升股票趋势预测准确度
  • QMI8658A_QMC5883L(9轴)-EVB 评估板
  • vue2+antd——实现动态菜单路由功能——基础积累
  • 代码随想录算法训练营第三十八天丨 动态规划part01
  • 关于集合遇到的坑
  • 需要下微信视频号视频的小伙伴们看过来~
  • 测试工具:hurl
  • RateLimiter限流
  • PMP适合哪些人去考?
  • 钡铼技术 工控机中的X86和ARM处理器:哪个更具可扩展性?
  • 软考 系统架构设计师系列知识点之软件构件(3)
  • 中科驭数亮相2023中国移动全球合作伙伴大会
  • WebGIS国产化(信创)研发流程一:数据库的调研与介绍
  • [Shell] ${} 的多种用法
  • 基于SpringBoot的社区医院管理系统设计与实现
  • Spring的执行流程与Bean的生命周期
  • 使用 SQL 的方式查询消息队列数据以及踩坑指南
  • 拿下国家级信创认证 中科驭数KPU SWIFT-2200N成为国内首款满足金融业严苛要求的DPU产品
  • centos怎么禁用和关闭selinux
  • 【LeetCode刷题日志】88.合并两个有序数组
  • 计算机考研 | 2013年 | 计算机组成原理真题
  • [Unity][VR]透视开发系列4-解决只看得到Passthrough但看不到Unity对象的问题
  • 电气工程 自动化 机械工科学生来看看
  • NewStarCTF2023week4-midsql(利用二分查找实现时间盲注攻击)
  • null,undefined的区别?
  • 2.flink编码第一步(maven工程创建)