Python 备忘&技巧收藏
1、中文注释
#coding:gbk或#coding:utf-8或##-*-
coding : gbk -*-
2、浮点数转换为十六进制:
>>> struct.pack("<f", 238.3).encode("hex") "cd4c6e43"
3、十六进制转换为浮点数
>>> import struct >>> struct.unpack("!f", "41973333".decode("hex"))[0] 18.899999618530273 >>> struct.unpack("!f", "41995C29".decode("hex"))[0] 19.170000076293945 >>> struct.unpack("!f", "470FC614".decode("hex"))[0] 36806.078125或者
from ctypes import * def convert(s): i = int(s, 16) # convert from hex to a Python int cp = pointer(c_int(i)) # make this into a c integer fp = cast(cp, POINTER(c_float)) # cast the int pointer to a float pointer return fp.contents.value # dereference the pointer, get the float print convert("41973333") # returns 1.88999996185302734375E1 print convert("41995C29") # returns 1.91700000762939453125E1 print convert("470FC614") # returns 3.6806078125E4
4、读写excel
读:
# -*- coding:utf-8 -*- import xlrd # 打开workbook workbook = xlrd.open_workbook("2.xlsx") # 抓取所有sheet页的名称 worksheets = workbook.sheet_names() print ("worksheet is %s" %worksheets) # 选择第一表格 worksheet_1 = workbook.sheets()[0] # 或者 worksheet_1 = workbook.sheet_by_index(0) """ # 遍历所有worksheet对象 for worksheet_name in worksheets: worksheet = workbook.sheet_by_name(worksheet_name) """ # 遍历sheet1的所有行row nrows = worksheet_1.nrows for cur_row in range(nrows): if cur_row == 0: continue row = worksheet_1.row_values(cur_row) print("row%s is %s" %(cur_row, row)) # 遍历sheet1的所有列 col ncols = worksheet_1.ncols for cur_col in range(ncols): if cur_col == 0: continue col = worksheet_1.col_values(cur_col) print("col%s is %s" %(cur_col, col)) # 遍历sheet1的所有单元格cell for rown in range(nrows): for coln in range(ncols): cell = worksheet1.cell_value(rown,coln) print cell # 获取单元格中值的类型 cell_type = worksheet1.cell_type(rown,coln) print cell_type写:
#coding=utf-8 import xlwt # 创建workbook和sheet对象 workbook = xlwt.Workbook() sheet1 = workbook.add_sheet("sheet1", cell_overwrite_ok=True) sheet2 = workbook.add_sheet("sheet2", cell_overwrite_ok=True) # 向sheet页中写入数据 sheet1.write(0,0,"a111") sheet1.write(0,1,"a222") sheet2.write(0,0,"b111") sheet2.write(1,0,"b222")
5、文件重命名、
#coding:utf-8 import os import os.path # 获得当前路径 curdir = os.getcwd() print curdir # 获得当前路径下的所有文件 文件夹 filelist = os.listdir(curdir) print filelist # 遍历所有对象 for files in filelist: # 如果是 rename.py 则跳过,不执行重命名 if files == "rename.py": continue # 原来文件路径 olddir = os.path.join(curdir,files) print "old dir is "+olddir # 判断是否文件夹,是则跳过 if os.path.isdir(olddir): print "is a folder ; continue" continue # 文件名 filename = os.path.splitext(files)[0] # 文件类型 filetype = os.path.splitext(files)[1] print "old name = "+filename print "old type = "+filetype # 新名称 newdir = os.path.join(curdir, "123" + filetype) # 重命名 os.rename(olddir, newdir)
6、面向对象
参考文章:http://www.cnblogs.com/dolphin0520/archive/2013/03/29/2986924.html
面向对象的三大特性:封装 继承 多态
类以及类中的方法在内存中只有一份,而根据类创建的每个对象都在内存中需要保存一份。
在python中,假如在属性名前加 2个下划线"__",则表明该属性是私有属性,否则为公有属性。(公有私有方法同理)
例如:访问私有属性需要类中访问
class People: __name = "Benjamin" __age = 20 def show_name(self): print self.__name def get_name(self): return self.__name p = People() print p.__name #错误 print p.__age #错误 p.show_name() #正确 print p.get_name() #正确
python类中有一些内置方法:
__init__(self, ...) 构造方法,支持重载,若没有定义,系统自动执行默认构造方法
__del__(self) 析构方法,支持重载,不需要显式调用
其他__cmp__(),__len()__等,可参考文章http://www.cnblogs.com/simayixin/archive/2011/05/04/2036295.html
7、
list有一个append方法,可以增加元素。以l这个列表为例,调用的方法是:l.append(1024)
删除list中的某一个元素,要用到del l[0]
list有两类常用操作:索引(index)和切片(slice)。
l[-1]表示l中的最后一个元素。
l[-3]表示倒数第3个元素。
8
httplib实现了http和https客户端请求,但urllib和urllib2对httplib进行了更上层的封装。
9
UnicodeDecodeError: ‘ascii’ code can’t decode byte 0xef in position 7: ordinal
not in range(128)
分析:路径存在中文,ASCII无法编码
解决方法: 在Python27/lib/site-packages下建立文件 sitecustomize.py,内容如下:
import sys
sys.setdefaultencoding("gb2312")
setdefaultencoding是设置python系统默认编码,gbk也可试试。