python常用标准库笔记

  1. os与操作系统相关,主要对文件和目录进行操作
import os
#导入模块,自带的不需要安装
os.mkdir("textdir")
#创建目录textdir
print(os.listdir("./"))
#查看当前目录有哪些文件
os.remove("textdir")
#删除目录textdir
print(os.getcwd())
#打印当前绝对路径


#练习:创建b文件夹,在b中有text01.txt文件
print(os.path.exists("b"))
#判断b是否存在
if not os.path.exists("b"):
    os.mkdir("b")
    #创建b文件夹
if not os.path.exists("b/text01.txt"):
#判断b中是否有text01文件
    f=open("b/text01.txt","w")
    f.write("hello,os using")
    f.close()
  1. time 模块
time.asctime()
#国外的时间格式
time.time()
#时间戳从1970年1月1日,00:00:00开始以秒计算
time.sleep()
#等待多少秒
time.localtime()
时间戳转换成时间元组
time.strftime()
#将当前时间戳转换成带格式的时间
#练习
print(time.asctime())
print("--------------------")
print(time.time())
print("--------------------")
print(time.localtime())
print(time.strftime("%Y-%m-%d %H:%M:%S" ,time.localtime() ))

image

#获取两天前的时间
now_timestamp = time.time()
tdayago_timestamp = now_timestamp - 60*60*24*2
print(time.strftime("%Y年%m月%d日 %H:%M:%S" ,time.localtime(tdayago_timestamp) ))
  1. erllib库
import urllib.request
response = urllib.request.urlopen("http://www.baidu.com")
#获取网络请求
print(response.status)
#返回状态
print(response.headers)
#获取返回的头部的信息


4. math库

import math

print(math.ceil(5.5))
#大于等于5.5的最小整数
print(math.floor(5.5))
#小于等于5.5的最大整数
print(math.sqrt(4))
#4的平方根

1 个赞