windows下python3 使用cx_Oracle,xlrd插件进行excel数据清洗录入
我们在做数据分析,清洗的过程中,很多时候会面对各种各样的数据源,要针对不同的数据源进行清洗,入库的工作。当然python这个语言,我比较喜欢,开发效率高,基本上怎么写都能运行,而且安装配置简单,基本上有网的环境pip install全部都搞定,没网的话,把whl包copy过来一行命令也就解决了(windows下python3.5使用pip离线安装whl包)。
本篇博客就针对,在windows平台下使用python3(python2社区将要停止支持,使用3是大势所趋),读取xls,xlsx格式的数据进行清洗入库做一个小例子。
初步业务流程
整个业务的流程十分简单:两个大的步骤
1. 读取xlsx数据进行清洗
2. cx_Oracle批量入库
建表语句:
create table temp_table
(
importtime varchar2(128),
carrier varchar2(32),
);
select * from temp_table
一个例子脚本:
# -*- coding: utf-8 -*-
import xlrd
import datetime
import cx_Oracle
import time
from itertools import islice
import os
os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.ZHS16GBK'
LineName = ['1号线','2号线']
StationName = []
########################链接数据库相关######################################
def getConnOracle(username,password,ip,service_name):
try:
conn = cx_Oracle.connect(username+'/'+password+'@'+ip+'/'+service_name) # 连接数据库
return conn
except Exception:
print(Exception)
#######################进行数据批量插入#######################
def insertOracle(conn,data,input_file_name):
sheetnumber = getSheetNumber(data)
cursor = conn.cursor()
try:
for x in range(0,sheetnumber):
templist = excel_table_byindex(input_file_name,0,x)
cursor.prepare('insert into temp_table(importtime ,carrier) values(:1,:2)')
# 使用cursor进行各种操作,templist数值需要和表temp_table对应
cursor.executemany(None,templist)
conn.commit()
except cx_Oracle.DatabaseError as msg:
print(msg)
finally:
cursor.close()
conn.close()
###########################打开excel文件########################
def openXLS(path):
try:
data = xlrd.open_workbook(path)
return data
except Exception:
print(Exception)
def getSheetNumber(data):
sheet_num = len(data.sheets())
return sheet_num
#######################一些数据清洗工作########################
def getlineName(str):
for x in LineName:
if x in str:
return x
def getStationName(str):
for x in StationName:
if x in str:
return x
##########将excel中除去表头的一个sheet读出来,返回一个list#############
def excel_table_byindex(path,colnameindex = 0,by_index = 0):
today = time.strftime('%Y%m%d', time.localtime(time.time()))
data = openXLS(path)
table = data.sheets()[by_index]
nrows = table.nrows
ncols = table.ncols
colnames = table.row_values(colnameindex)
list = []
for rownum in range(1,nrows):
row = table.row_values(rownum)
temp_lineName = getlineName(row[6])
temp_stationName = getStationName(row[6])
if row:
app = [today, str(row[1]), str(row[2]),temp_stationName,temp_lineName]
# for i in range(len(colnames)):
# app[colnames[i]] = row[i]
list.append(app)
return list
###################一个可以从文件第二行开始读的办法#############
def getAllStationName(path):
StationName_file = open(path, 'r', encoding='utf-8')
#count = len(StationName_file.readlines())
for line in islice(StationName_file,1,None):
str_temp = line.strip('\n')
if str_temp not in LineName and str_temp !='----'and str_temp!='':
StationName.append(str_temp)
####################################################################
def getStationNamefromexcel(path):
data = openXLS(path)
table = data.sheets()[0]
nrows = table.nrows
ncols = table.ncols
colnames = table.row_values(0)
list = []
for rownum in range(0,nrows):
row = table.row_values(rownum)[0]
if row:
list.append(row)
return list
#################################################################
def main():
username = 'xx'
password = 'xx'
ip = '192.168.1.1'
service_name = 'iop'
#获取数据库链接
conn = getConnOracle(username,password,ip,service_name)
input_file_name = (r"E:\code\python\findS\subwayBase\xx.xlsx")
#output_file_name = input("Enter the output file name:")
getAllStationName(r"E:\code\python\findS\subwayBase\站点.txt")
begin = datetime.datetime.now()
insertOracle(conn,openXLS(input_file_name),input_file_name)
# x.fetchone()
# c.close() # 关闭cursor
# conn.close() # 关闭连接
end = datetime.datetime.now()
print((end - begin).seconds)
if __name__ =='__main__':
main()
python3 windows下使用cx_Oracle操作oracle的报错问题
报错信息如下:
Traceback (most recent call last):
File "E:/code/python/findS/findSubwayBase.py", line 134, in <module>
main()
File "E:/code/python/findS/findSubwayBase.py", line 124, in main
insertOracle(conn,openXLS(input_file_name),input_file_name)
File "E:/code/python/findS/findSubwayBase.py", line 32, in insertOracle
cursor.executemany(None,templist)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-6: ordinal not in range(128)
Process finished with exit code 1
在使用python3 的cx_Oracle操作oracle数据时候,不可避免的会遇到中文的编码问题,当然,上网一搜全是python2的,解决方案是:
#在开头加上
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
python3中的解决方案为:加上核心代码
import os
os.environ['NLS_LANG']='SIMPLIFIED CHINESE_CHINA.ZHS16GBK'
就ok啦,其实就是设置一下客户端编码 ,参考:python编码 OS.ENVIRON详解
xlrd 操作excel
demo代码:
#获取一个工作表
table = data.sheets()[0] #通过索引顺序获取
table = data.sheet_by_index(0) #通过索引顺序获取
table = data.sheet_by_name(u'Sheet1')#通过名称获取
#获取整行和整列的值(数组)
table.row_values(i)
table.col_values(i)
#获取行数和列数
nrows = table.nrows
ncols = table.ncols
#循环行列表数据
for i in range(nrows ):
print table.row_values(i)
#单元格
cell_A1 = table.cell(0,0).value
cell_C4 = table.cell(2,3).value
#使用行列索引
cell_A1 = table.row(0)[0].value
cell_A2 = table.col(1)[0].value
#简单的写入
row = 0
col = 0
# 类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
ctype = 1 value = '单元格的值'
xf = 0 # 扩展的格式化
table.put_cell(row, col, ctype, value, xf)
table.cell(0,0) #单元格的值'
table.cell(0,0).value #单元格的值'
参考链接
[OS.ENVIRON详解]: http://blog.csdn.net/junweifan/article/details/7615591
[python编码]:http://www.cnblogs.com/fkissx/p/5417363.html
再次强烈推荐,精通oracle+python系列:官方文档
http://www.oracle.com/technetwork/cn/articles/dsl/mastering-oracle-python-1391323-zhs.html
离线版本下载链接:
http://download.csdn.net/detail/wangyaninglm/9815726
windows下python3 使用cx_Oracle,xlrd插件进行excel数据清洗录入的更多相关文章
- windows下python3.6 32bit 安装django
在Windows下python3.6安装Django1.11.3 1.首先下载地址:https://pypi.python.org/pypi/Django/1.11.3 pip install dja ...
- windows下python3.6安装pycryto or crypto or pycryptodome与使用
pycrypto,pycrytodome和crypto是一个东西,在很久以前,crypto在python上面的名字是pycrypto它是一个第三方库,但是已经停止更新三年了,所以不建议安装这个库: w ...
- Windows下python3登陆和操作linux服务器
一.环境准备 python3远程连接需要用到pycrytodome和paramiko库,其中后者依赖前者,所以按照顺序来安装 1. 安装pycrytodome 1 pip install pycryt ...
- Windows下python3生成UTF8的CSV文件和sha256sum踩坑记录
CSV的坑 在Ubuntu下是简单的写入完事 import csv ... with open(filename, 'w') as output: f = csv.writer(output) f.w ...
- Windows下Python3+nose+appium自动化测试之Android篇
[本文出自天外归云的博客园] 简介 以下用来做自动化测试的这款app叫最爱抓娃娃,以后会改名为网易抓娃娃. 下文提到的appiumier项目里会包含用来测试的apk包以及自动化测试代码. 先说一个坑 ...
- Windows下Python3.7的安装
1.下载Python3官网地址:www.python.org当前最新版本为Python 3.7.3. Windows下有个6个下载链接Windows x86-64 embeddable zip fil ...
- windows下python3.7安装gmpy2、Crypto 库及rsa
基于python3.7在windows下安装gmpy2 先检查一下是否安装了wheel文件包,在cmd中输入wheel,查看一下,如果没有安装,则输入安装:pip install wheel 如果遇到 ...
- [No000054] Windows 下Python3.5, NoteBook增强版安装
接着上周继续,没看的童鞋.请移步: http://www.cnblogs.com/Chary/p/No00004B.html 这里,假设你已经能够看到这个画面了: 接下来,我们继续 给药 : 安装no ...
- windows 下的tcping 小插件
如果把插件放在根目录 就要能过cmd切换到根目录 cd \ c:\>tcping -d -t -i 0.06 www.baidu.com 将文件放在c:\WINDOWS\system32目录下, ...
随机推荐
- nyoj-737--石子合并(一)(动态规划)
石子合并(一) 时间限制:1000 ms | 内存限制:65535 KB 难度:3 描述 有N堆石子排成一排,每堆石子有一定的数量.现要将N堆石子并成为一堆.合并的过程只能每次将相邻的两堆 ...
- 图论之tarjan缩点
缩点,就是把一张有向有环图中的环缩成一个个点,形成一个有向无环图. 首先我介绍一下为什么这题要缩点(有人肯定觉得这是放屁,这不就是缩点的模板题吗?但我们不能这么想,考试的时候不会有人告诉你打什么板上去 ...
- 新手村,学会做人选数 https://www.luogu.org/problemnew/show/P1036
#include<cstdio> #include<cmath> #include<string.h> using namespace std; int n,k,s ...
- BZOJ 2301 莫比乌斯函数+分块
思路: 同BZOJ1101 就是加个容斥 - http://blog.csdn.net/qq_31785871/article/details/54340241 //By SiriusRen #inc ...
- 细数SuperComputer最新排名和常见Benchmark类型
在网络层,互联网提供所有应用程序都要使用的两种类型的服务,尽管目前理解这些服务的细节并不重要,但在所有TCP/IP概述中,都不能忽略他们: 无连接分组交付服务(Connectionless Packe ...
- 【原创】JMS生产者和消费者【PTP异步接收消息】
PTP模式下,异步接收消息需要定义一个MessageListener来监听,当生产者有消息要发送时会主动通知Listener去处理该消息,会调用监听的onMessage方法去处理. 首先看生产者(和同 ...
- php如何实现文件下载
php如何实现文件下载 1. 设置超链接的href属性 <ahref="文件地址"></a> 如果浏览器不能解析该文件,浏览器会自动下载.而如果文件是图片或 ...
- ActiveMQ学习笔记(18)----Message高级特性(二)
1. Blob Message 有些时候,我们需要传递Blob(Binary Large Objects)消息,在5.14之前,(5.12和5.13需要在jetty.xml中手动开启)可以按照如下的方 ...
- 路飞学城Python-Day12
7月10日安排 完成所有函数作业和思维导图整理 [45.函数-生成器] 如果数据是有规律的,就可以先生成一个数据,等数据执行的时候再执行,也就是在真正调用数据之前,拿到数据的生成规律,而是拿到生 ...
- [agc011e]increasing numbers
题意: 如果一个十进制非负整数的所有数位从高位到低位是不减的,我们称它为“上升数”,例如1558,11,3,0都是上升数,而10,20170312则不是: 给定整数N,求最小的k使得N能被表示为k个上 ...