python-day5内置模块time、range、sys、os、shelve、xml、max等

时间:2022-05-19 18:50:41

@os树状目录

import os,os.path

def showdir(path,depth):
    if depth==0:
        print(path)
    for item in os.listdir(path):
        print("|    "*depth + "+--"+item)
        new_path=os.path.join(path,item)
        if os.path.isdir(new_path):
            showdir(new_path,depth+1)
            
            
path=r"F:\一行代码"
showdir(path,0)

@os.walk()

for root, dirs, files in os.walk(path):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))

返回的是一个三元组(root,dirs,files)。

  • root 所指的是当前正在遍历的这个文件夹的本身的地址
  • dirs 是一个 list ,内容是该文件夹中所有的目录
  • files 同样是 list , 内容是该文件夹中所有的文件
  • root+dir和root+file

@程序内置找路径

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__) ) )#__file__代表当前文件名
a=os.path.abspath(__file__)
b=os.path.dirname(os.path.abspath(__file__) ) print(BASE_DIR)
print(a)
print(b)

运行结果:

F:\lianxi\little_case
F:\lianxi\little_case\慕课scrapy\lalal.py
F:\lianxi\little_case\慕课scrapy

@装饰器的作用不在于验证登录,更重要的是验证登录状态。主程序做登录标记,其他页根据主程序登记进行判断。

@引入模块相关解释:

  • import time实质是解释执行了time并将结果赋值给time
  • 如果要导入包,就要在包里面的__init__文件里import包里其它文件。

@os模块

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd
os.curdir 返回当前目录: ('.')
os.pardir 获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2') 可生成多层递归目录
os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename("oldname","newname") 重命名文件/目录
os.stat('path/filename') 获取文件/目录信息
os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep 输出用于分割文件路径的字符串
os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command") 运行shell命令,直接显示
os.environ 获取系统环境变量
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间

@sys模块

sys.argv           命令行参数List,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(0)
sys.version 获取Python解释程序的版本信息
sys.maxint 最大的Int值
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]
sys.path.append(x)#增加搜索路径

@time库

>>> time.gmtime()#默认传time.time()
time.struct_time(tm_year=2018, tm_mon=9, tm_mday=1, tm_hour=15, tm_min=0, tm_sec=22, tm_wday=5, tm_yday=244, tm_isdst=0)
>>> time.localtime()#默认传time.time()
time.struct_time(tm_year=2018, tm_mon=9, tm_mday=1, tm_hour=23, tm_min=0, tm_sec=29, tm_wday=5, tm_yday=244, tm_isdst=0)
>>> tuple_time=(2018,1,10,1,11,24,2,10,0)
>>> time.asctime(tuple_time)#只能传9位元组的参数,不传就是默认传time.localtime();元组转字符串
'Wed Jan 10 01:11:24 2018'
>>> time.asctime()
'Sat Sep 1 23:04:03 2018'
>>> time.ctime()#结果同asctime(),但是此处传参浮点数,或者默认time.time();浮点数转字符串
'Sat Sep 1 23:09:44 2018'
>>> time.strftime("%Y-%H",time.localtime())#默认localtime();元组以字符串format转字符串
'2018-23'
>>>time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
time.struct_time(tm_year=2016, tm_mon=5, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=143, tm_isdst=-1)

>>> time.mktime(time.strptime("2016/05/22","%Y/%m/%d"))#localtime()的反函数

1463846400.0

对应关系

Directive    Meaning    Notes
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM. (1)
%S Second as a decimal number [00,61]. (2)
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
All days in a new year preceding the first Sunday are considered to be in week 0. (3)
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53].
All days in a new year preceding the first Monday are considered to be in week 0. (3)
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM,
where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].
%Z Time zone name (no characters if no time zone exists).
%% A literal '%' character.

转换图:

python-day5内置模块time、range、sys、os、shelve、xml、max等

python-day5内置模块time、range、sys、os、shelve、xml、max等

@datetime库

>>> import datetime

>>> datetime.datetime.now()

datetime.datetime(2018, 9, 2, 15, 22, 32, 44303)
>>> datetime.date.fromtimestamp(time.time()) datetime.date(2018, 9, 2)
>>> datetime.datetime.now() + datetime.timedelta(3) datetime.datetime(2018, 9, 5, 15, 23, 58, 639256)
>>> datetime.datetime.now() + datetime.timedelta(hours=3) datetime.datetime(2018, 9, 2, 18, 24, 27, 836926)
>>> datetime.datetime.now().replace(minute=3,hour=2) datetime.datetime(2018, 9, 2, 2, 3, 16, 674719)
>>>

@random模块

import random
print (random.random()) #0.6445010863311293
#random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0
print (random.randint(1,7)) #
#random.randint()的函数原型为:random.randint(a, b),用于生成一个指定范围内的整数。
# 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
print (random.randrange(1,10)) #
#random.randrange的函数原型为:random.randrange([start], stop[, step]),
# 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),
# 结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
# random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
print(random.choice('liukuni')) #i
#random.choice从序列中获取一个随机元素。
# 其函数原型为:random.choice(sequence)。参数sequence表示一个有序类型。
# 这里要说明一下:sequence在python不是一种特定的类型,而是泛指一系列的类型。
# list, tuple, 字符串都属于sequence。有关sequence可以查看python手册数据模型这一章。
# 下面是使用choice的一些例子:
print(random.choice("学习Python"))#学
print(random.choice(["JGood","is","a","handsome","boy"])) #List
print(random.choice(("Tuple","List","Dict"))) #List
print(random.sample([1,2,3,4,5],3)) #[1, 2, 5]
#random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。

实例

import random
import string
#随机整数:
print( random.randint(0,99)) # #随机选取0到100间的偶数:
print(random.randrange(0, 101, 2)) # #随机浮点数:
print( random.random()) #0.2746445568079129
print(random.uniform(1, 10)) #9.887001463194844 #随机字符:
print(random.choice('abcdefg&#%^*f')) #f #多个字符中选取特定数量的字符:
print(random.sample('abcdefghij',3)) #['f', 'h', 'd'] #随机选取字符串:
print( random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )) #apple
#洗牌#
items = [1,2,3,4,5,6,7]
print(items) #[1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print(items) #[1, 4, 7, 2, 5, 3, 6]
@生成随机验证码
import random
checkcode = ''
for i in range(4):
current = random.randrange(0,4)
if current != i:
temp = chr(random.randint(65,90))
else:
temp = random.randint(0,9)
checkcode += str(temp)
print (checkcode)

@max

d1 = {'name': 'egon', 'price': 100}
d2 = {'name': 'rdw', 'price': 666}
d3 = {'name': 'zat', 'price': 1}
l1 = [d1, d2, d3]
a = max(l1, key=lambda x: x['name'])
print(a)
b = max(l1, key=lambda x: x['price'])
print(b) #结果
{'name': 'zat', 'price': 1}
{'name': 'rdw', 'price': 666}
a=[1,2,3,4,5,6,7,1,2,3,4,1,2,3,2]
print(max(a,key=a.count))
#2
 

  python-day5内置模块time、range、sys、os、shelve、xml、max等

@更多:

http://blog.51cto.com/egon09/1840425

@

@configparser模块,YAML语法(配置文件用),

http://www.cnblogs.com/alex3714/articles/5161349.html

@字典就是hashlib(哈希)做的。

@hashlib模块,用于加密相关,可以判断网站首页是否被篡改。

@sha比md5复杂,sha用最大的,但是最大的效率也低。

@正则表达式