1 有输入参数
import sys, os
if len(sys.argv) < 3:
print 'input invalid'
exit(1)
a = sys.argv[1]
b = sys.argv[2]
if not a.isdigit() or not b.isdigit():
print 'input is not digit'
exit(1)
2 打开文件错误捕捉
try:
f1 = open(str(i))
except IOError, e:
print 'cannot open file ' + str(i)
i += 1
continue
line = f1.readline()
dic = eval(line)
f1.close()
3 用urllib和urllib2发送post请求
body = urllib.urlencode({
'token':token,
'task':'{"TaskName":"testScipt"}'})
returnedReq = urllib2.Request(
url = 'http://www.test.com/',
data = body)
returnedResult = urllib2.urlopen(returnedReq).read()
returnedResult = returnedResult.strip()
print returnedResult
4 操作excel
import xlrd
data = xlrd.open_workbook('test.xlsx')
table = data.sheets()[0] #选择第一个工作区
cols = table.col_values(0) #选择第一列
print len(cols)
5 使用eval()或ast.literal_eval() 出现错误
NameError: name ‘total_count’ is not defined或ValueError: malformed string
比如原始字符串是 str = '{"name":"jgy","age":null}'
转为字典时会发现null不是一个字符串,就当做变量,但是没有定义(python认可的是Null True False 注意第一个字母大写),所以出错,相应的实际过程中可能还会到 ‘true’ is not defined, ‘false’ is not defined类似的等等。
既然没定义,在前面定义一下就行了,比如自己定义 null = 'null', true = 'true'..
还有个想法,可以用正则把冒号后面的不是数字也没加引号的value值给加上引号。
6 时间
获取最简洁日期格式:
>>>time.strftime('%Y-%m-%d',time.localtime(time.time()))
'2013-07-04'
获取上一秒时间:
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time() - 1))
将一个字符串时间转为python时间格式
str1 = '2013-06-03 20:07:41'
str2 = '2013-06-03 20:08:43'
time1= time.strptime(str1,"%Y-%m-%d %H:%M:%S") #time1 is time_struct type
time1= time.strptime(str2,"%Y-%m-%d %H:%M:%S")
#now we wanna to 取得time1和time2的时间差
#需要转为datetime,然后使用datetime的timedelta方法
datetime1 = datetime.datetime(*time1[:6])
datetime2 = datetime.datetime(*time2[:6])
datedelta = datetime2 - datetime1
print datedelta
#datetime.timedelta(0, 62) #后面是秒数
seconds = delta.seconds #获取int型秒数
7 海量数据去重
>>> a = [11,22,33,44,11,22]
>>> b = set(a)
>>> b
set([33, 11, 44, 22])
>>> c = [i for i in b]
>>> c
[33, 11, 44, 22]
8