python 常用BIF记

python 常用 BIF 记

1.import time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
time.time()  # 返回时间戳 float
time.ctime(sec) # 将当前(或sec时间戳)的时间 返回为字符串 'Thu Mar 24 18:53:35 2016'
time.strftime() # 格式化输出

>>>time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
'2016-03-24 18:58:00'
>>>time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
'Thu Mar 24 19:00:00 2016'

time.mktime() # 格式化输入,转化成时间戳

>>>a = "Sat Mar 28 22:24:24 2009"
>>>b = time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

time.sleep(sec) # 线程推迟 sec 秒运行
time.clock() # 第一次调用返回程序运行时间,以后每次调用都返回与第一次调用的时间间隔

2. import random

1
2
3
4
5
6
7
random.random()  # 生成一个0到1的随机浮点数
random.uniform(a,b) # 生成 a-b范围内的随机浮点数,a,b 都包括
random.randint(a,b) # 生成 a-b范围内的随机整数
random.randrange(a,b,c) # a-b范围内步长为c的序列内随机取一个数
random.choice(sequence) # **在 sequence (有序类型,list,tuple,str 等), 随机选取一个元素**
random.shuffle(list) # 将列表中的元素打乱
random.sample(sequence,k) 从 sequence 中随机获取k长度的片段,不会改变sequence序列

3. import os

1
2
3
4
5
6
7
8
9
10
11
12
13
os.getcwd()  # 当前工作目录
os.listdir(dir) # 当前 dir 下的所有文件和目录
os.remove() / os.rmdir() # 删除文件/目录
os.mkdir() # 创建目录
os.path.isfile() / os.path.isdir() # 是否文件/目录,主要是字符串匹配,需要传入完整路径(绝对或相对)
os.path.exists() # 制定对象是否存在
os.path.split() # 返回路径的目录和文件名(按最后一个 / 分开)
os.path.getsize() # 获得文件大小
os.path.abspath() # 获得绝对路径
os.path.john() # 连接目录和文件名
os.system('order') # 执行 shell 命令 order

os.chdir() # 改变当前工作目录

4. csv

1
2
3
4
5
6
7
8
9
10

import csv
# 读文件和读取其他文件差不多,逐行分割以逗号读取即可

# 写文件:
csvfile = open('csvfilename.csv','w')
writer = csv.writer(csvfile)
writer.writerow(['','','']) # 写一行
writer.writerows(data) # 写多行
csvfile.close() # 调用close方法关闭