1.OS模块
import os
os.getcwd()
os.chdir('home/py')
os.listdir('home/py')
os.mkdir('boy')
os.makedirs('/home/sy/a/b/c/d')
os.rmdir('boy')
os.removedirs('/home/sy/a/b/c/d')
os.renanme('02.txt','002.txt')
os.chmod()
os.path.basename(‘path/filename’)
os.path.dirname(‘path/filename’)
os.path.join(path1[,path2[,...]])
os.path.split('path')
os.path.splitext()
os.path.getatime\ctime\mtime()
os.path.getsize()
os.path.exists()
os.path.isabs()
os.path.abspath(name)
os.path.isdir()
os.path.isfile()
os.path.islink()
os.path.realpath(path)
os.path.relpath(path[, start])
os.path.normcase(path)
os.path.join(dirname,basename)
os.path.ismount()
os.path.samefile()
os.path.commonprefix(list)
os.path.lexists()
os.path.expanduser(path)
os.path.expandvars(path)
os.path.sameopenfile(fp1, fp2)
os.path.samestat(stat1, stat2)
os.path.splitdrive(path)
os.path.walk(path, visit, arg)
os.path.supports_unicode_filenames()
2.sys模块
import sys
sys.argv
sys.path
sys.modules.keys()
sys.modules
sys.exc_info()
sys.exit(n)
sys.hexversion
sys.version
sys.platform
sys.maxint
sys.maxunicode
sys.stdout
sys.stdout.write(‘aaa‘)
sys.stdout.writelines()
sys.stdin
sys.stdin.read()
sys.stderr
sys.exc_clear()
sys.exec_prefix
sys.byteorder
sys.copyright
sys.api_version
sys.version_info
sys.getdefaultencoding()
sys.getfilesystemencoding()
sys.builtin_module_names
sys.executable
sys.getwindowsversion()
sys.stdin.readline()
3.time模块
import time
time.time()
time.localtime()
"""
timestamp to struct_time 本地时间 time.struct_time(tm_year=2019, tm_mon=12, tm_mday=10, tm_hour=1, tm_min=20, tm_sec=24, tm_wday=1, tm_yday=344, tm_isdst=0):tm_year(年) 比如2011
tm_mon(月) 1 - 12
tm_mday(日) 1 - 31
tm_hour(时) 0 - 23
tm_min(分) 0 - 59
tm_sec(秒) 0 - 61
tm_wday(weekday) 0 - 6(0表示周日)
tm_yday(一年中的第几天) 1 - 366
tm_isdst(是否是夏令时) 默认为-1
"""
time.gmtime()
time.strftime("%Y-%m-%d %X",time.localtime())
"""
%a 本地(locale)简化星期名称
%A 本地完整星期名称
%b 本地简化月份名称
%B 本地完整月份名称
%c 本地相应的日期和时间表示
%d 一个月中的第几天(01 - 31)
%H 一天中的第几个小时(24小时制,00 - 23)
%I 第几个小时(12小时制,01 - 12)
%j 一年中的第几天(001 - 366)
%m 月份(01 - 12)
%M 分钟数(00 - 59)
%p 本地am或者pm的相应符
%S 秒(01 - 61)
%U 一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。
%w 一个星期中的第几天(0 - 6,0是星期天)
%W 和%U基本相同,不同的是%W以星期一为一个星期的开始。
%x 本地相应日期
%X 本地相应时间
%y 去掉世纪的年份(00 - 99)
%Y 完整的年份
%Z 时区的名字(如果不存在为空字符)
%% ‘%’字符
"""
time.asctime(time.localtime())
time.ctime(time.time())
4.datetime模块
import datetime
datetime.date.today()
datetime.date.isoformat(obj)
datetime.date.fromtimestamp()
datetime.date.weekday(obj)
datetime.date.isoweekday(obj)
datetime.date.isocalendar(obj)
datetime.datetime.today()
datetime.datetime.now([tz])
datetime.datetime.utcnow()
datetime.fromtimestamp(timestamp[,tz])
datetime.utcfromtimestamp(timestamp)
datetime.datetime.strptime(‘2019-12-10 12:21:21‘,”%Y-%m-%d %H:%M:%S”)
datetime.datetime.strftime(datetime.datetime.now(), ‘%Y%m%d %H%M%S‘)
datetime.date.today().timetuple()
5.hashlib模块
import hashlib
string = "beyondsoft"
md5 = hashlib.md5()
md5.update(string.encode('utf-8'))
res = md5.hexdigest()
print("md5加密结果:",res)
sha1 = hashlib.sha1()
sha1.update(string.encode('utf-8'))
res = sha1.hexdigest()
print("sha1加密结果:",res)
sha256 = hashlib.sha256()
sha256.update(string.encode('utf-8'))
res = sha256.hexdigest()
print("sha256加密结果:",res)
sha384 = hashlib.sha384()
sha384.update(string.encode('utf-8'))
res = sha384.hexdigest()
print("sha384加密结果:",res)
sha512= hashlib.sha512()
sha512.update(string.encode('utf-8'))
res = sha512.hexdigest()
print("sha512加密结果:",res)
high = hashlib.md5(b'beyondjie')
high.update(string.encode('utf-8'))
res = high.hexdigest()
print("采用key加密:",res)
6.random模块
random.random()
random.uniform(a, b)
random.randint(a, b)
random.randrange([start], stop[, step])
random.choice(sequence)
random.shuffle(x[, random])
random.sample(sequence, k)
7.string
str.capitalize()
str.center(width)
str.ljust(width)
str.rjust(width)
str.zfill(width)
str.count(str,[beg,len])
str.decode(encodeing[,replace])
str.encode(encodeing[,replace])
str.endswith(substr[,beg,end])
str.startswith(substr[,beg,end])
str.expandtabs(tabsize = 8)
str.find(str,[stat,end])
str.index(str,[beg,end])
str.isalnum()
str.isalpha()
str.isdecimal()
str.isdigit()
str.islower()
str.isupper()
str.isnumeric()
str.isspace()
str.title()
str.istitle()
str.join(seq)
str.split(str=‘‘,num)
str.splitlines(num)
str.lower()
str.upper()
str.swapcase()
str.lstrip()
str.rstrip()
str.strip()
str.partition(substr)
str.replace(str1,str2,num)
str.rfind(str[,beg,end])
str.rindex(str,[beg,end])
str.rpartition(str)
str.translate(str,del=‘‘)
8.urllib模块
import urllib.request
import urllib.parse
import json
url = "http://www.baidu.com"
parsed = urllib.parse.urlparse(url)
print(parsed)
url = "http://www.baidu.com"
new_path = urllib.parse.urljoin(url,"index.html")
print(new_path)
req = urllib.request.urlopen('http://www.baidu.com')
print(req.read())
file_name = urllib.request.urlretrieve('http://www.baidu.com','%s/baidu.html'%BASE_DIR)
dic = {'name':'melon','age':18}
data = urllib.parse.urlencode(dic)
print(data)
dic = {'name':'melon','age':18}
data = urllib.parse.urlencode(dic)
req = urllib.request.urlopen('http://127.0.0.1:8000/index?%s'%data)
content = req.read()
dic = {'name':'melon','age':18}
data = urllib.parse.urlencode(dic)
req = urllib.request.Request('http://127.0.0.1:8000/index', data.encode())
opener = urllib.request.urlopen(req)
content = json.loads(opener.read().decode())
9.re模块
'.'
‘-’
'*'
'+'
'^'
‘$’
'\' # 转义字符, 使后一个字符改变原来的意思,如果字符串中有字符*需要匹配,可以\*或者字符集[*] re.findall(r'3\*','3*ds')结['3*']
'*'
‘?’
'{m}'
'{n,m}'
'\d'
'\D'
'\w'
'\W'
'\s'
'\S'
'\A'
'\Z'
'\b'
'\B'
'(?P<name>...)'
[]
re.match(pattern, string, flags=0)
re.search(pattern, string, flags=0)
re.findall(pattern, string, flags=0)
re.finditer(pattern, string, flags=0)
re.sub(pattern, repl, string, count=0, flags=0)
re.sub('(blue|white|red)','colour', 'blue socks and red shoes')
y = re.split(r'\W+','This is a test, short and sweet, of split().')
print(y)
10.math模块
函数 | 使用说明 |
---|
ceil(x) | 取大于等于x的最小的整数值,如果x是一个整数,则返回x |
copysign(x,y) | 把y的正负号加到x前面,可以使用0 |
fabs(x) | 返回x的绝对值(float类型) |
factorial(x) | 取x阶乘的值 |
floor(x) | 取小于等于x的最大整数值,如果x是一个整数,返回自身 |
fmod(x,y) | 得到x/y的余数,返回float类型 |
frexp(x) | 返回一个元组(m,e),其计算方式为:x分别除以0.5和1,得到一个值的范围 |
fsum(iterable) | 对迭代器里的每个元素进行求和操作 |
gcd(x,y) | 返回x和y的最大公约数 |
isclose(a,b,*,rel_tol=1e-09,abs_tol=0.0) | 如果值a和彼此接近,则返回True,否则返回False;rel_tol是相对容差-它是a和b之间允许的最大差值。abs_tol是最小绝对容差—对于接近0的比较有用 |
isfinite(x) | 如果x既不是无穷也不是NAN,则返回True;否则返回False |
isinf(x) | 如果x是正无穷大或负无穷大,则返回True,否则返回False |
isnan(x) | 如果x不是数字,返回True |
modf(x) | 返回由x的小数部分和整数部分组成的元组 |
trunc(x) | 返回x的整数部分 |
exp(x) | 返回e**x |
expm1(x) | 返回e**(x-1) |
log(x[,base]) | 返回x的自然对数,默认以e为基数;base参数给定时,将x的对数返回给定的base |
log1p(x) | 返回1+x的自然对数(基数e)。计算结果的方式对于接近零的x是准确的 |
log2(x) | 返回x基数为2的对数。通常比log(x,2)更准确 |
log10(x) | 返回x基数为10的对数。通常比log(x,10)更准确 |
pow(x,y) | 返回x的y次方,即x**y |
sqrt(x) | 返回x的平方根 |
pi | 数学常量Π=3.1415926…,可用精度 |
e | 数学常量e=2.718281…,可用精度 |
tau | 数学常量\tau=6.283185···,可用精度。Tau是一个等于2\pi的圆常量,即圆的周长与其半径之比 |
11.json模块
import json
json.dumps()
dict = {"name":"Tom", "age":23}
print(json.dumps(dict))
with open("test.json", "w", encoding='utf-8') as f:
f.write(json.dumps(a, indent=4))
f.close()
json.loads('{"name":"Tom", "age":23}')
with open("test.json", "r", encoding='utf-8') as f:
aa = json.loads(f.read())
f.seek(0)
bb = json.load(f)
print(aa)
print(bb)
+---------------------------+-------------------------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str | string |
+-------------------+---------------+
| int, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+