程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

python模块

发布于2019-08-20 13:53     阅读(142)     评论(0)     点赞(18)     收藏(4)


python的优点在于有大量3的内置模块和第三方模块,使用这些模块我们可以方便地实现需要的功能。本文主要介绍python的模块结构及常用的内置模块和第三方模块。

1. 模块简介

模块即包括python声明及定义的文件。一个python文件就是一个模块。如编写一个test.py文件,我们需要将这个文件作为模块导入,只需要这样写:import test 。这样我们就把test.py作为模块导入到当前文件,可以使用该模块定义的功能。模块名可以使用全局变量__name__得到。

import os
import re
from datetime import datetime

print(os.__name__)
print(re.__name__)

if __name__ == "__main__":
    pass
# 结果
os
re
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

在上面代码中,可以看到有一行:if __name__ == “__main__”:,这行代码为模块提供了一个便于测试的用户接口。当我们直接运行该文件时,__name__变量值为"__main__",结果为True,可直接运行。当作为第三方模块导入时,__name__变量为模块名,结果为False,不能运行该文件,但我们可使用该文件内部定义的功能。因此我们编写python文件时,通常在该行代码上面定义功能(函数、类等),在下面定义执行代码,便于检验功能正确性。

除此之外,我们可以使用包来组织模块,避免模块名的冲突。实质上,包就是一个包含多个python文件的目录。注意:该目录下一定有一个__init__.py文件,该文件表示当前目录是一个包。除此之外,包目录下一般有一个__pycache__目录,该目录会缓存每个模块编译后的文件(.pyc文件:)。执行某个模块时,会检查源文件与编译版文件的修改日期确定是否需要重新编译。当我们导入模块时,解释器会搜索当前目录,所有已安装模块和第三方模块。搜索路径可通过sys模块的path变量获取。如:

>>> import sys
>>> sys.path
['D:\\software\\PyCharm 2018.1.1\\helpers\\pydev', 'E:\\Code exercise\\Code-exercise\\python', 'E:\\graduation-project', 'D:\\software\\PyCharm 2018.1.1\\helpers\\pydev', 'E:\\env-python\\Scripts\\python36.zip', 'E:\\env-python\\DLLs', 'E:\\env-python\\lib', 'E:\\env-python\\Scripts', 'd:\\software\\python3\\Lib', 'd:\\software\\python3\\DLLs', 'E:\\env-python', 'E:\\env-python\\lib\\site-packages', 'E:\\env-python\\lib\\site-packages\\dlib-19.10.0-py3.6-win-amd64.egg', 'D:\\software\\PyCharm 2018.1.1\\helpers\\pycharm_matplotlib_backend', 'E:\\Code exercise\\Code-exercise\\python', 'E:\\graduation-project', 'E:/Code exercise/Code-exercise/python']
  • 1
  • 2
  • 3

2. 常用内置模块

2.1 os模块

os模块封装了常见的文件和目录操作。下面列举常用的方法:

附菜鸟教程的os模块:https://www.runoob.com/python3/python3-os-file-methods.html

img

2.2 日期时间模块

附菜鸟教程的时间日期模块参考:https://www.runoob.com/python3/python3-date-time.html

time模块

time模块包含多个有关时间处理的函数。下表显示常用方法:

方法 说明
time.time() 返回以秒为单位的浮点数时间(unix时间戳,从1970-01-01 00:00:00 UTC)
time.clock() 返回处理器时间
time.sleep() 休眠n秒
time.ctime() 将以秒表示的时间(time.time())转换为当地时间的字符串
time.localtime() 将秒为单位的时间转换为表示当地时间的时间元组
time.gmtime() 将秒为单位的时间转换为UTC时间的时间元组
time.asctime() 将时间元组转换为当地时间的字符串
time.mktime() 将时间元组转换为挂钟时间
import time

print(time.time())   # 返回以秒为单位的浮点数时间(unix时间戳,从1970-01-01 00:00:00 UTC)
print(time.clock())  # 返回处理器时间
print(time.ctime())  # 将以秒表示的时间(time.time())转换为当地时间的字符串
for x in range(3):
    print('hello world')
    time.sleep(0.1)  # 休眠n秒
print(time.asctime())  # 将时间元组转换为当地时间的字符串
print(time.localtime())  # 将秒为单位的时间转换为表示当地时间的时间元组
print(time.gmtime())  # 将秒为单位的时间转换为UTC时间的时间元组
print(time.mktime(time.localtime()))  # 将时间元组转换为挂钟时间
# 结果
1525878891.406281
4.276538056912168e-07
Wed May  9 23:14:51 2018
hello world
hello world
hello world
Wed May  9 23:14:51 2018
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=9, tm_hour=23, tm_min=14, tm_sec=51, tm_wday=2, tm_yday=129, tm_isdst=0)
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=9, tm_hour=15, tm_min=14, tm_sec=51, tm_wday=2, tm_yday=129, tm_isdst=0)
1525878891.0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

datetime模块

datetime模块对time模块进行了封装。包含多个有关日期时间处理的函数。

方法 说明
datetime.now() 返回一个datetime对象,表示当地时间
datetime.utcnow() 返回一个datetime对象,表示UTC时间
object_datetime.timestamp() 将一个datetime对象转换为unix时间戳
datetime.fromtimestamp() 将Unix时间戳转换为datetime对象
datetime.strftime() 将datetime对象格式化输出为字符串
datetime.strptime() 将时间字符串转换为datetime对象
from datetime import datetime

print(datetime.now())  # 返回一个datetime对象,表示当地时间
print(datetime.utcnow())  # 返回一个datetime对象,表示UTC时间
test_time = datetime.utcnow()
print(test_time.timestamp())  # 将一个datetime对象转换为unix时间戳
print(datetime.fromtimestamp(1525849091.98994))  # 将Unix时间戳转换为datetime对象
print(datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S.%f'))  # 将datetime对象格式化输出为字符串
print(datetime.strptime('2018-05-09 23:04:12.119774', '%Y-%m-%d %H:%M:%S.%f'))  # 将时间字符串转换为datetime对象
# 结果
2018-05-09 23:14:51.708639
2018-05-09 15:14:51.708639
1525850091.708639
2018-05-09 14:58:11.989940
2018-05-09 23:14:51.708639
2018-05-09 23:04:12.119774
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
2.3 collections模块

python内置的集合模块,提供很多有用的集合类。

namedtuple:命名元组,为一个函数,可用来创建一个自定义的tuple对象。其可规定元素的个数,并可使用属性(不是索引)来访问某个元素 语法:namedtuple(‘name’, [元素])

import collections

Circle = collections.namedtuple('Circle', ['x', 'y', 'z'])
print(isinstance(Circle, tuple))
circle = Circle(5, 6, 7)
print(circle.x, circle.y, circle.z)

# 执行结果
False
5 6 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

deque:列表list为先行存储,数据量较大时,插入删除效率较低。deque是可实现高效插入和删除的双向列表,适合用于队列和栈。deque不仅实现了list的append和pop,还支持appendleft()和popleft().

import collections

deque_list = collections.deque([1, 2, 3])
print(type(deque_list))
deque_list.appendleft(5)
deque_list.append(6)
print(deque_list)

# 执行结果
<class 'collections.deque'>
deque([5, 1, 2, 3, 6])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
2.4 hashlib模块

提供常用的摘要算法,如MD5,SHA1等。摘要算法:通过一个函数,将任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示)

import hashlib

md5 = hashlib.md5()
md5.update("how to use md5 in python hashlib?".encode('utf-8'))
print(md5.hexdigest())

# 执行结果
d26a53750bc40b38b65a520292f69306
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
2.5 urllib模块

提供了一系列操作URL的功能,可用来模拟浏览器执行get post等请求

from urllib import request

with request.urlopen("http://www.baidu.com") as f:
    data = f.read()
    print("status:", f.status, f.reason)
    for k, v in f.getheaders():
        print("%s: %s" % (k, v))
print('Data:', data.decode('utf-8'))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8


所属网站分类: 技术文章 > 博客

作者:天下

链接:https://www.pythonheidong.com/blog/article/49418/d9d04c9289c2364c9ae9/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

18 0
收藏该文
已收藏

评论内容:(最多支持255个字符)