常用模块1:os、time、random

函数可提升代码阅读性、可重复使用

函数执行的时候只会把函数的执行文件路径添加到sys.path里,故在执行文件之外的模块(py文件)时使用import需要指定相对执行文件的相对路径否则会找不到文件;也可以自己添加相关文件到sys.path里(sys.path.append(路径))

os.path.dirname(os.path.abspath()) 可以获取到当前文件的路径

多个函数封装成模块(py文件)

# 当前文件的路径
pwd = os.getcwd()
# 当前文件的父路径
father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + ".")
# 当前文件的前两级目录
grader_father = os.path.abspath(os.path.dirname(pwd) + os.path.sep + "..")
# 当前用户路径
print(os.path.join(os.path.expanduser('~')))
# 桌面
print(os.path.join(os.path.expanduser('~'), "Desktop"))

 

多个模块封装成包(用来组织模块)

包文件夹下有__init__.py文件(init文件主要是引入当前模块用: from . import test )

通常使用bin.py作为包的入口(如果不想被调用,就把代码块放在 if __name__=="__main__" 下边)

重要模块:logging模块,re模块,json模块,time模块

time模块常用函数:

时间戳:time.time()  表示1970年1月1日起到当前共经历了多少秒

time.localtime()  本地化时间(含年月日、时分秒、星期……)

time.strftime("%Y-%m-%d)   字符串时间

时间戳转换为结构化时间:结构化时间=time.localtime(时间戳)

结构化时间转换为时间戳:时间戳=mktime(结构化时间)

结构化时间转字符串时间:字符串时间=strftime(结构化时间)

结构化时间=strptime(字符串时间,时间格式)

 

 

 

 随机数字:

random.random()  0-1之间的随机浮点数

random.randint(1,9) 1-9之间的随机数
chr(random.randint(65,122))  a-Z之间的随机字母
random.shuffle([1,2,3]) # 转换为随机序列

 

posted @ 2021-01-16 15:36  虾米维生素  阅读(71)  评论(0编辑  收藏  举报