1. 程式人生 > >八、python操作excel及網絡編程和異常處理

八、python操作excel及網絡編程和異常處理

size let finally 必須 新的 異常信息 屬性 開發 tar

一、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 = {
"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 = {‘username‘:‘小怪‘,"money":8888}
cookie = {‘token1111‘:"ajajja"}
res = requests.post(cookie_url,data=data,cookies=cookie).json()#使用cookies參數指定cookie
print(res)
# head_url = ‘http://api.nnzhp.cn/getuser2‘
# data = {‘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及網絡編程和異常處理