python 常用操作
1. 读取文件
fd = open(file)
for i in fd.read().split('
'):
print i
或者
fp = open('test.txt', 'r')
while True:
line = fp.readline().strip() #去掉后面的回车
if line:
print line
打开文件覆盖写
fd_pre = open(PRE_FILE, "w+")
if not fd_pre.read():
fd_pre.write('tes11
')
else:
fd_pre.write('tes11
')
2. 字典删除一个key
>>> dic = dict()
>>> dic['k1'] = 'v1'
>>> dic['k2'] = 'v2'
>>> dic
{'k2': 'v2', 'k1': 'v1'}
>>> del dic['k1']
>>> dic
{'k2': 'v2'}
3. 获取参数
from optparse import OptionParser, OptionGroup
def parse_argv(argv = sys.argv[1:])
parser = OptionParser(usage = 'Usage: python %prog [options]',
version = '%prog v0.1, release version',
description = "DESC: %prog operatrion")
parser.add_option('-s', '--source',
dest = 'source',
help = "source")
parser.add_option('-k', '--keyword',
dest = 'keyword',
help = "source")
parser.add_option('-t', '--target',
dest = 'target',
help = "target")
(options, args) = parser.parse_args(argv)
if not options.source or not options.keyword or not options.target:
parser.print_help()
sys.exit(1)
return (options, args)
4. 将字符串转化为时间
>>> import datetime
>>> a = '2016-02-03 04:02:37'
>>> datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S")
datetime.datetime(2016, 2, 3, 4, 2, 37)
5. python时间比较
6. python获取标准时间
>>> import time
>>> time.strftime("%Y-%m-%d %X", time.localtime(time.time()))
>>> import datetime