1. 模块调用
同一目录下调用,直接from xx import xx就行
不同目录下调用,最好是import sys;sys.path.append()
调用其他模块时,Python会依次在项目当前路径、Python path、Python安装目录下寻找。
2. 异常
所有异常继承自BaseException,BaseException、Exception可接受所有异常类型
try:
except:
else:#没有异常时执行
finally:有无异常都会执行
excel的操作
前提,安装三个包,xlrd、xlwt、xlutils
1 #coding=utf-8 2 3 import xlrd 4 #1.打开excel 路径用双斜线 5 wb=xlrd.open_workbook("D:\test\testweek3.xls") 6 ''' 7 #2.获取sheet页 S需要大写 8 sh=wb.sheet_by_name("Sheet1") 9 #3.获取单元格的值 cell_value(i,j) 第i+1行,第j+1列 10 user=sh.cell_value(1,0) 11 print user 12 13 #练习1:读取第二个sheet页,获取第三行,第三列的值 14 sh2=wb.sheet_by_name('test2') 15 age=sh2.cell_value(2,2) #整数默认输出类型为float,需要转换为整型 16 print int(age) 17 18 #练习2:读取第一个sheet页中所有用户信息--循环 19 sh3=wb.sheet_by_name('Sheet1') 20 for i in range(1,5): #从excel第二行开始读取,从数字1开始 21 user=sh3.cell_value(i,0) 22 print user 23 ''' 24 #练习3:第一个sheet,输出用户名和密码,密码转换规则(如果为空,直接输出密码,不为空则转换) 25 sh4=wb.sheet_by_name('Sheet1') 26 #行数 r_num 27 r_num=sh4.nrows 28 for i in range(1,r_num): 29 user=sh4.cell_value(i,0) 30 pwd=sh4.cell_value(i,1) 31 if pwd=="": 32 print user,pwd 33 else: 34 print user,int(pwd)
1 #coding=utf-8 2 ''' 3 excel的写入 4 ''' 5 import xlrd 6 from xlutils.copy import copy 7 #将C:Python27xlutils-1.7.1xlutils复制到C:Python27Libsite-packages下 8 #1.打开excel 9 wb=xlrd.open_workbook("D:\test\testweek3.xls") 10 #2.复制原来的excel,变为一个新的excel 11 new_wb=copy(wb) 12 #3.获取sheet页,并写入值get_sheet(i)第i+1个sheet页 13 sh=new_wb.get_sheet(1) 14 sh.write(3,4,'51testing') 15 #4.保存 16 new_wb.save("D:\test\testweek3.xls")
1 #coding=utf-8 2 import xlrd 3 4 path = 'D:\Documents\Personal\appium\documents\three-day' 5 exe = xlrd.open_workbook(path +'\test.xls') 6 sh = exe.sheet_by_index(0) 7 num = sh.nrows 8 i = 1 9 while(i<num): 10 user = sh.cell_value(i,0) 11 pwd = sh.cell_value(i,1) 12 i = i + 1 13 if pwd =='': 14 print user,pwd 15 else: 16 print user ,int(pwd)
1 #coding=utf-8 2 import xlrd 3 from xlutils.copy import copy 4 path = 'D:\Documents\Personal\appium\documents\three-day\source' 5 exe = xlrd.open_workbook(path +'\test.xls') 6 exe_new = copy(exe) 7 sh = exe_new.get_sheet(0) 8 # copy之后的,只能编辑保存,不能获取print sh.cell_value(0,0) 9 sh.write(0,5,'testing') 10 exe_new.save(path+'\test1.xls') 11 12 exe1 = xlrd.open_workbook(path+'\test1.xls') 13 sh = exe1.sheet_by_index(0) 14 print sh.cell_value(0,5)