目录

5.1 模块与包

在命令行输入以下,检查模块是否存在

python -c "import 模块名"



表示没有相应的模块。

对于自定义模块,可以采用首字母大写来避免与标准库重复。

5.1.1 包

Graphics/
__init__.py
Bmp.py
Jpeg.py
Png.py
Tiff.py
Xpm.py

上面目录包含了__init__.py文件,使其成了一个包。只要包目录是程序目录的子目录,或者存在于Python路径中,就可以导入这些模块。

import Graphics.Bmp

若我们编辑__init__.py为:

#__init__.py
__all__ = ['Bmp', 'Jpeg', 'Png', 'Tiff', 'Xpm']

那么,就可以使用下面的命令:

from Graphics import *

多层嵌套也可以的。

Tips docstring 测试 doctest

#testdoc.py
def simpledoc(real, dream='sky'):
""" Returns the text I can not control now... real is any string; dream is the same as well, while it has default value 'sky'.
Of course, your different people has various dreams, but we all need to confront
the real life.
>>> simpledoc('god')
'haha happy'
>>> simpledoc('god', 'earth')
"don't cry, go forward..."
""" if real == 'god' and dream == 'sky':
return "haha happy"
else:
return "don't cry, go forward..." if __name__ == "__main__":
import doctest
doctest.testmod()

在命令行内输入(路径啥的得弄好)

python testdoc.py -v

得到:

Trying:
simpledoc('god')
Expecting:
'haha happy'
ok
Trying:
simpledoc('god', 'earth')
Expecting:
"don't cry, go forward..."
ok
1 items had no tests:
__main__
1 items passed all tests:
2 tests in __main__.simpledoc
2 tests in 2 items.
2 passed and 0 failed.
Test passed.

5.2 Python 标准库概览

5.2.1 字符串处理

String

Struct

struct模块提供了struct.pack(), struct.unpack()以及其他一些函数,还提供了struct.Struct()类。struct.pack()函数以一个struct格式化字符串以及一个或多个值为参数,并返回一个bytes对象,其中存放的是按照改格式规范表示的所有这些参数值。

data = struct.pack("<2h", 11, -9) # data == b'\x0b\x00\xf7\xff'
items = struct.unpack("<2h", data) # items == (11,-9)
TWO_SHORTS = struct.Struct("<2h")
data = TWO_SHORTS.pack(11, -9)
items = TWO_SHORTS.unpack(data) # (data, items)

格式是"<2h",表示,将俩个有符号的16位整数以小端的方法打包在一起,其中:

"\x0b\x00" 表示11,事实上,11的16进制表示为"0x000b",以小端的方式存储就是"\x0b\x00",即低位在前,高位在后。

"\xf7\xff"表示-9,-9的16进制表示为"\xff\xf7",注意,因为是负数,所以-9需要通过9的补码来表示。9 --> 0b00001001, 其反码为:0b11110110, 补码等于反码加1:0b11110111, 所以,16进制就是:"\xff\xf7"

另外: "<H16s" 表示 第一个参数为16位无符号整数, 第二个参数为长度16的字节字符串。

符号 符号说明
< little-endian 小端 低位 --> 高位
> | ! big-endian 大端 高位 --> 低位
b 8位有符号整数
B 8位无符号整数
h 16位有符号整数
H 16位无符号整数
i 32位有符号整数
I 32位无符号整数
q 64位有符号整数
Q 64位无符号整数
f 32位浮点数
d 64位浮点数
? 布尔型
s bytes或bytearray

difflib

re

io.StringIO 类

sys.stdout = io.StringIO()

5.2.3 命令行设计

fileinput

optparse

5.2.4 数学与数字

int

float

complex

decimal

fractions

math

cmath 用于复数数学函数

random

Tips isinstance(a, type)

isinstance(1, int) #True
isinstance(1.0, int) #False
isinstance(1.0, str) #False
isinstance([], list) #list

Scipy

Numpy

5.2.5 时间与日期

import calendar, datetime, time

moon_datetime_a = datetime.datetime(1969, 7, 20,
20, 17, 40) #datetime.datetime(1978, 7, 20, 20, 17, 40)
moon_time = calendar.timegm(moon_datetime_a.utctimetuple()) #269813860
moon_datetime_b = datetime.datetime.utcfromtimestamp(moon_time) #datetime.datetime(1978, 7, 20, 20, 17, 40)
moon_datetime_a.isoformat() #datetime.datetime(1978, 7, 20, 20, 17, 40)
moon_datetime_b.isoformat() #datetime.datetime(1978, 7, 20, 20, 17, 40)
time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(moon_time)) #'1978-07-20T20:17:40'

calendar

datatime

dateutil

mxDateTime

5.2.7 算法与组合数据类型

bisect

heapq

collections

array

weakref

5.2.8 文件格式、编码与数据持久性

base64 --> RFC 3548

quopri --> quoted-printable

uu --> uuencoded

xdrlib

bz2 --> .bz2

gzip --> .gz

tarfile --> .tar | .tar.gz | .tar.bz2

zipfile --> .zip

aifc --> AIFF

wave --> .wav

audioop

sndhdr

configparser

pickle

shelve

DBM

5.2.9 文件、目录与进程处理

Shutil

tempfile --> 临时文件与目录

filecmp --> 文件目录的比较

subprocess | multiprocessing

os --> 对操作系统功能的访问接口

date_from_name = {}
path = "."
for name in os.listdir(path):
fullname = os.path.join(path, name)
if os.path.isfile(fullname):
date_from_name[fullname] = os.path.getmtime(fullname)
date_from_name
import os, collections

data = collections.defaultdict(list)
path = "C:/Py" #or "C:\\Py"
for root, dirs, files in os.walk(path):
for filename in files:
fullname = os.path.join(root, filename)
key = (os.path.getsize(fullname), filename)
data[key].append(fullname) for key, value in data.items(): print(key, value)

5.2.10 网络与Internet程序设计

socket --> 大多数基本的网络功能

http.cookies, http.cookiejar --> 管理cookies

http.client --> HTTP请求

urllib

html.parser --> 分析HTML XHTML

urllib.parse --> URL

urllib.robotparser --> robots.txt

json --> JSON

xmlrpc.client, xmlrpc.server --> XML-RPC

ftplib --> FTP

nntplib --> NNTP

telnetlib --> TELNET

smtpd --> SMTP

smtplib --> SMTP

imaplib --> IMAP4

poplib --> POP3

mailbox --> Mailboxes

email

Django

Turbogears

Zope

5.2.11 XML

xml.dom --> DOM

xml.dom.minidom --> DOM

xml.sax --> SAX

xml.etree.ElementTree

Python Revisited Day 05(模块)的更多相关文章

  1. Python(五)模块

    本章内容: 模块介绍 time & datetime random os sys json & picle hashlib XML requests ConfigParser logg ...

  2. python函数和常用模块(三),Day5

    递归 反射 os模块 sys模块 hashlib加密模块 正则表达式 反射 python中的反射功能是由以下四个内置函数提供:hasattr.getattr.setattr.delattr,改四个函数 ...

  3. Python自动化之常用模块

    1 time和datetime模块 #_*_coding:utf-8_*_ __author__ = 'Alex Li' import time # print(time.clock()) #返回处理 ...

  4. Python常用内建模块

    Python常用内建模块 datetime 处理日期和时间的标准库. 注意到datetime是模块,datetime模块还包含一个datetime类,通过from datetime import da ...

  5. Day5 - Python基础5 常用模块学习

    Python 之路 Day5 - 常用模块学习   本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shel ...

  6. Python一路走来 - 模块

    模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才 ...

  7. Python多线程(threading模块)

    线程(thread)是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务. ...

  8. python 学习day5(模块)

    一.模块介绍 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能 ...

  9. Python之旅Day6 模块应用

    time datetime random os sys shutil pickle json shelv xml configparser hashlib subprocess logging re ...

随机推荐

  1. Springboot 系列(二)Spring Boot 配置文件

    注意:本 Spring Boot 系列文章基于 Spring Boot 版本 v2.1.1.RELEASE 进行学习分析,版本不同可能会有细微差别. 前言 不管是通过官方提供的方式获取 Spring ...

  2. .NET: 使用.NET Core CLI开发应用程序

    要开发.NET Core应用程序,除了使用强大的Visual Studio之外,还可以使用.NET Core CLI..NET Core CLI (Command-Line Interface),也就 ...

  3. 聊聊 API Gateway 和 Netflix Zuul

    最近参与了公司 API Gateway 的搭建工作,技术选型是 Netflix Zuul,主要聊一聊其中的一些心得和体会. 本文主要是介绍使用 Zuul 且在不强制使用其他 Neflix OSS 组件 ...

  4. 浅谈Java虚拟机内存中的对象创建,内存布局,访问定位

    参考于 深入理解Java虚拟机 这里介绍HotSpot虚拟机(自带的虚拟机) 1.对象的创建 对于程序员来说,创建对象的方法: User user1 = new User(); User user2 ...

  5. java开发环境配置——IDEA SVN的使用

    一.安装svn客户端,在idea中配置svn 装小乌龟,TortoiseSVN ,就下图一个要注意的地方,这里默认 command line client tools是不安装的,选上.如果已经安装过了 ...

  6. SpringBoot Web学习笔记

    一.资源的访问: 情形一.所有的  /webjars/**  都会去 classpath:/META_INFO/resource/webjars/ 下找资源: webjars:以jar包的方式引入静态 ...

  7. Android Button四种点击事件和长按事件

    项目XML代码 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:andr ...

  8. DVWA 黑客攻防演练(九) SQL 盲注 SQL Injection (Blind)

    上一篇文章谈及了 dvwa 中的SQL注入攻击,而这篇和上一篇内容很像,都是关于SQL注入攻击.和上一篇相比,上一篇的注入成功就马上得到所有用户的信息,这部分页面上不会返回一些很明显的信息供你调试,就 ...

  9. 微信小程序基本目录结构学习

    今天我们就以firstdemo为例,介绍一下小程序的基本目录结构.当我们打开一个微信小程序项目后,点击进入“编辑”菜单,我们可以看到有以下5个文件/文件夹):pages文件夹,utils文件夹,全局文 ...

  10. sqlserver 清空数据 主键从1开始

    TRUNCATE  TABLE  TbName   --TbName是表名 表清空数据之后 使新增加的记录保持从1 开始