0
点赞
收藏
分享

微信扫一扫

python标准库

彪悍的鼹鼠 2021-09-19 阅读 58

一、python常用的标准库

1、python标准库常见模块

  • 操作系统相关:os
  • 时间与日期:time,datetime
  • 科学计算:math
  • 网络请求:urllib

2、os模块

  • os模块主要对文件、目录对操作
  • 常见的方法
os.mkdir() 创建目录
os.removedirs() 删除文件
os.getcwd() 获取当前目录
os.path.exists(dir or file) 判断文件或者目录是否存在
import os

# 创建一个目录
os.mkdir('testdir')
# 查看当前目录的文件,以列表的形式返回
print(os.listdir('./'))
# 删除目录
os.removedirs('testdir')
# 获取当前路径
print(os.getcwd())
# 可以用这个判断当前路径下文件是否存在,false代表不存在
print(os.path.exists('b'))
if not os.path.exists('b'):
    os.mkdir('b') 
if not os.path.exists('b/test.txt'):
    f = open('b/test.txt', 'w')
    f.write('hello sumemr')
    f.close()

3、time模块

  • 获取当前时间以及时间格式的模块
  • 导入方式-imprort time
  • 常用的方法
time.asctime() 国外的时间格式
time.time() 时间戳
time.sleep() 等待
time.localtime() 时间戳转成时间元组
time.strftime() 将当前的时间戳转成带格式的时间
格式:time.strftime("%Y-%m-%d%H-%M-%S",time.localtime())
import time

print(time.asctime())
print(time.time())
print(time.localtime())
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
# 获取三天前的时间
import time

print(time.time())
now_timestamp = time.time()
three_day_before = now_timestamp - 60*60*24*3
time_tuple = time.localtime(three_day_before)
print(time.strftime('%Y-%m-%d %H:%M:%S', time_tuple))

4、urllib库

  • 请求URL
1)python2
import urllib2
response = urllib2.urlopen('http://www.baidu.com')
2) python3
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')
print(response.status)
print(response.read())
print(response.headers)

5、math库

  • 科学计算库
  • math.ceil(x) 返回大于等于参数x的最小整数
  • math.floor(x) 返回小于等于参数x的最大整数
  • math.sqrt(x) 平方根
import math
# 向上取整
print(math.ceil(5.5))
# 向下取整
print(math.floor(5.5))
# 平方根
print(math.sqrt(36))
  • 打印出
6
5
6.0
举报

相关推荐

0 条评论