当前位置: 首页 > 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()

相关文章:

  • 支持CT、MR三维后处理的医学PACS源码
  • 【Luogu】 P5642 人造情感(emotion)
  • AUTOSAR汽车电子嵌入式编程精讲300篇-基于车联网的商用车载终端系统的研究与设计
  • 关于多个elementui的cascader级联组件页面滚动渲染样式导致卡顿问题
  • SQLSmith: Databend 如何利用随机化测试检测 Bug
  • MySQL 8 - 处理 NULL 值 - is null、=null、is not null、<> null 、!= null
  • Jupyter Notebook的使用
  • 数据结构【DS】B树
  • Postman如何导出接口的几种方法?
  • Ubuntu Studio 23.10发布
  • 【开源】基于SpringBoot的天然气工程运维系统的设计和实现
  • NlogPrismWPF
  • Vue+ElementUI项目打包部署到Ubuntu服务器中
  • 苹果cms模板MXone V10.7魔改版源码 全开源
  • 如何公网远程访问本地WebSocket服务端
  • 【347天】每日项目总结系列085(2018.01.18)
  • 【402天】跃迁之路——程序员高效学习方法论探索系列(实验阶段159-2018.03.14)...
  • 【mysql】环境安装、服务启动、密码设置
  • 002-读书笔记-JavaScript高级程序设计 在HTML中使用JavaScript
  • android 一些 utils
  • Angular 4.x 动态创建组件
  • Angular js 常用指令ng-if、ng-class、ng-option、ng-value、ng-click是如何使用的?
  • CSS3 聊天气泡框以及 inherit、currentColor 关键字
  • CSS中外联样式表代表的含义
  • DataBase in Android
  • ES10 特性的完整指南
  • interface和setter,getter
  • Java IO学习笔记一
  • Java读取Properties文件的六种方法
  • Linux链接文件
  • Mocha测试初探
  • PAT A1050
  • php ci框架整合银盛支付
  • PHP 程序员也能做的 Java 开发 30分钟使用 netty 轻松打造一个高性能 websocket 服务...
  • react 代码优化(一) ——事件处理
  • React中的“虫洞”——Context
  • Yeoman_Bower_Grunt
  • 编写符合Python风格的对象
  • 设计模式 开闭原则
  • 深入体验bash on windows,在windows上搭建原生的linux开发环境,酷!
  • 十年未变!安全,谁之责?(下)
  • 微信小程序:实现悬浮返回和分享按钮
  • 移动互联网+智能运营体系搭建=你家有金矿啊!
  • 在Unity中实现一个简单的消息管理器
  • 正则表达式
  • 追踪解析 FutureTask 源码
  • ​一文看懂数据清洗:缺失值、异常值和重复值的处理
  • #我与Java虚拟机的故事#连载18:JAVA成长之路
  • #预处理和函数的对比以及条件编译
  • (6)STL算法之转换
  • (delphi11最新学习资料) Object Pascal 学习笔记---第8章第2节(共同的基类)
  • (javascript)再说document.body.scrollTop的使用问题
  • (Ruby)Ubuntu12.04安装Rails环境
  • (大众金融)SQL server面试题(1)-总销售量最少的3个型号的车及其总销售量
  • (附源码)spring boot建达集团公司平台 毕业设计 141538