首页 > 代码库 > 八、python操作excel及网络编程和异常处理

八、python操作excel及网络编程和异常处理

一、python操作excel

1、读excel,xlrd模块用来读excel

# book = xlrd.open_workbook(r‘students.xlsx‘)
#打开excel
# print(book.sheet_names())
#获取所有sheet的名字
# sheet = book.sheet_by_index(0)
#根据sheet页的位置去取sheet
# sheet2 = book.sheet_by_name(‘Sheet2‘)
#根据sheet页的名字获取sheet页
# print(sheet.nrows)#获取sheet页里面的所有行数
# print(sheet.ncols)#获取sheet页里面的所有列数
# print(sheet.row_values(0))
#根据行号获取整行的数据
# print(sheet.col_values(0))
##根据列获取整列的数据
# print(sheet.cell(1,1).value)
#cell方法是获取指定单元格的数据,前面是行,后面是列
# lis = []
# for i in range(1,sheet.nrows):
# #i代表的是每一行,因为第一行是表头,所以直接从第二行开始循环
# d = {}
# id = sheet.cell(i,0).value#行是不固定的,列是固定的
# name = sheet.cell(i,1).value
# sex = sheet.cell(i,2).value
# d[‘id‘]=int(id)
# d[‘name‘]=name
# d[‘sex‘]=sex
# lis.append(d)
# print(lis)
#读excel的时候,xls xlsx都可以读

2、写excel,xlwt模块用来读excel

lis = [{‘id‘: 1, ‘name‘: ‘小明‘, ‘sex‘: ‘男‘},
{‘id‘: 2, ‘name‘: ‘小黑‘, ‘sex‘: ‘男‘},
{‘id‘: 3, ‘name‘: ‘小怪‘, ‘sex‘: ‘男‘},
{‘id‘: 4, ‘name‘: ‘小白‘, ‘sex‘: ‘女‘}]
new_lis = [
[1,‘小明‘,‘男‘],
[2,‘小明‘,‘男‘],
[3,‘小明‘,‘男‘],
[4,‘小明‘,‘男‘],
[5,‘小明‘,‘男‘],
[6,‘小明‘,‘男‘]
]
title = [‘编号‘,‘姓名‘,‘性别‘]
# import xlwt
# book = xlwt.Workbook()
# #新建一个excel对象
# sheet = book.add_sheet(‘stu‘)
# #添加一个sheet页
# # sheet.write(0,0,‘编号‘)
# # book.save(‘stu.xls‘)
# for i in range(len(title)):
# #title多长,循环几次
# sheet.write(0,i,title[i])
# #i既是lis的下标,也代表每一列
# #处理表头
# #写excel的时候,你保存的文件名必须是xls
# for row in range(len(lis)):
# #取lis的长度,控制循环次数
# id = lis[row][‘id‘]
# #因为lis里面存的是一个字典,lis[row]就代表字典里面的每个元素,然后字典取
# #固定的key就可以了
# name = lis[row][‘name‘]
# sex = lis[row][‘sex‘]
# new_row = row+1#因为循环的时候是从0开始循环的,第0行是表头,不能写
# #要从第二行开始写,所以这里行数要加一
# sheet.write(new_row,0,id)
# sheet.write(new_row,1,name)
# sheet.write(new_row,2,sex)
#
# book.save(‘new_stu.xls‘)

3、xlutils模块

  xlutils模块用来修改excel的内容,不能直接修改原来的excel内容,必须得先复制一个新的excel,然后对这个新的excel进行修改,用法如下:

from xlutils.copy import copy
book = xlrd.open_workbook(‘new_stu.xls‘)
#打开原来的excel
new_book = copy(book)
#通过xlutils里面copy复制一个excel对象
sheet = new_book.get_sheet(0)
#获取sheet页
sheet.write(0,0,‘id‘)
new_book.save(‘new_stu_1.xls‘)

二、python网络编程

from urllib.request import urlopen
from urllib.parse import urlencode,quote,quote_plus,unquote,unquote_plus
import json
url = ‘http://python.nnzhp.cn/get_sites‘
#quote把特殊字符变成url编码
url2 = ‘https://www.baidu.com/s?wd=sdfsdfsdf%3A%2F%3A%22&rsv_spt=1&rsv_iqid=0xaa8e074900029bd6&issp=1&f=8&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=baiduhome_pg&rsv_enter=0&inputT=5072&rsv_t=dcbeEpYrzUynvhHzvkLSB6mnuZdC0rSBEilp4crIXEm8r98NibNI82Yw4NL2MnKw%2FSzM&rsv_sug3=28&oq=sdfsdfsdf%2520%2526lt%253B%25202%25202%2526lt%253B%25204%25202&rsv_pq=b4570bd80002e2e5&rsv_sug1=11&rsv_sug7=100&rsv_sug2=0&rsv_sug4=5634‘
#unquote就是把url编码变成原来字符串
#url编码
# res = urlopen(url).read().decode()
#发送get请求
# new_res = json.loads(res)
#把返回的json转成python的数据类型
#urlopen(url)这个是发送get请求

data = http://www.mamicode.com/{
"username":"hahahahahahah",
"password":"123456",
"c_passwd":"123456"
}
param = urlencode(data).encode()
# print(urlopen(url2,param).read().decode())
#发post请求
#requests模块就是基于urllib模块开发的

import requests
# requests.get(url).text
#text方式返回的是字符串
# res = requests.get(url).json()
#返回的json


#post请求
url_reg = ‘http://python.nnzhp.cn/reg?username=lhl&password‘ \
‘=123456&c_passwd=123456‘
# res = requests.post(url_reg).json()
# print(type(res),res)
url_set = ‘http://python.nnzhp.cn/set_sties‘
d = {
"stie":"hahfsdfsdf",
"url":"http://www.nnzhp.cn"
}
# res = requests.post(url_set,json=d).json()
# print(res)
cookie_url = ‘http://python.nnzhp.cn/set_cookies‘

data = http://www.mamicode.com/{‘username‘:‘小怪‘,"money":8888}
cookie = {‘token1111‘:"ajajja"}
res = requests.post(cookie_url,data=http://www.mamicode.com/data,cookies=cookie).json()#使用cookies参数指定cookie
print(res)
# head_url = ‘http://api.nnzhp.cn/getuser2‘
# data = http://www.mamicode.com/{‘userid‘: 1}
# header = {‘Content-Type‘: "application/json"}
# res = requests.post(url, headers=header).json()

up_url = ‘http://python.nnzhp.cn/upload‘
file = {‘file_name‘:open(‘aaa.py‘)}
res = requests.post(up_url,files=file).text
print(res)

三、异常处理

info  = {
"id":1,
"name":"xiaobai",
"sex":"nan"
}
# # chioce = input(‘请输入你要查看的属性:‘)
# try:
# 5/0
# except Exception as e:
# #这个exception 能捕捉到所有的异常
# #python3
# #这个是出了异常的话,怎么处理,e代表异常信息
# print(‘你输入的key不存在‘,e)
# else:
# #没有出异常的话,走这里
# print(‘没有出异常的话,走这里‘)
# finally:
# #不管有没有出异常都会走
# print(‘这里是finally‘)
import pymysql
def OpertionMysql(sql,port=3306,charset=‘utf8‘):
host = ‘211.149.218.16‘
user = ‘byz‘
passwd = ‘123456‘
db =‘bt_st‘
try:
conn = pymysql.connect(
host=host,user=user,passwd=passwd,port=port,
db=db,charset=charset
)#建立连接
except Exception as e:
return {"code":308,"msg":"数据库连接异常%s"%e}
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
#建立游标
try:
is_correct_sql(sql)
cur.execute(sql)
except Exception as e:
return {"code":309,"msg":"sql错误!%s"%e}
else:
if sql.startswith(‘select‘): # 判断是什么语句
res = cur.fetchone()
else:
conn.commit()
res = 88
return res
finally:
cur.close()
conn.close()
#执行sql

def is_float(s):
try:
float(s)
except Exception as e:
return False
return True

class SQLERR(Exception):
def __str__(self):
return ‘SQL异常hahahhahahfdsfsdflkj4k324324‘

def is_correct_sql(sql):
#select
# update insert delete truncate drop create alter
sql_start = [‘select‘,‘update‘,‘insert‘,‘delete‘]
if sql.startswith(sql_start[0]) or sql.startswith(sql_start[1])\
or sql.startswith(sql_start[2]) or sql.startswith(sql_start[3]):
return True
else:
raise SQLERR
#主动抛出异常


# is_correct_sql(‘sdfsdfsdfsdf‘)
res = OpertionMysql(‘xxxxxx‘)

print(res)
#raise是主动抛出一个异常,如果在被调用的函数里
#没有捕捉异常的话,在它上一级调用的函数里面也可以捕捉到

八、python操作excel及网络编程和异常处理