目录

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. .net core使用ViewComponent将页面图片转码成base64

    using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; usi ...

  2. [ASP.NET] 如何利用Javascript分割檔案上傳至後端合併

    最近研究了一下如何利用javascript進行檔案分割上傳並且透過後端.特地記錄一下相關的用法 先寫限制跟本篇的一些陷阱 1.就是瀏覽器的支援了 因為本篇有用到blob跟webworker 在ie中需 ...

  3. linux查看和修改PATH环境变量的方法

    查看PATH:echo $PATH以添加mongodb server为列修改方法一:export PATH=/usr/local/mongodb/bin:$PATH//配置完后可以通过echo $PA ...

  4. html标签种类很多,为什么不都用div?

    why not divs? 所有html页面标签都可以用div解决,为什么还会存在各种不同的标签呢? 代码是写给机器阅读的,初始化标签更利于快速编程,毕竟很多标签有了自定义属性,无需编码控制,可维护性 ...

  5. ionic3 Loading组件的用法

    import { LoadingController } from 'ionic-angular'; @Component({ selector: 'page-contact', templateUr ...

  6. Kotlin入门(31)JSON字符串的解析

    json是App进行网络通信最常见的数据交互格式,Android也自带了json格式的处理工具包org.json,该工具包主要提供了JSONObject(json对象)与JSONArray(json数 ...

  7. (办公)SpringBoot和swagger2的整合.

    因为开发项目的接口需要给app,小程序测试,所以用swagger. 1.pom.xml: <dependency><!--添加Swagger依赖 --> <groupId ...

  8. Spark之Pipeline处理模式

    一.简介 Pipeline管道计算模式:只是一种计算思想,在数据处理的整个流程中,就想水从管道流过一下,是顺序执行的. 二.特点 1.数据一直在管道中,只有在对RDD进行持久化[cache,persi ...

  9. MongoDB副本集及C#程序的连接配置

    1.副本集 高可用是绝大多数数据库管理系统的核心目标之一.如果要想生产数据在发生故障后依然可用,就需要确保为生产数据库多部署一台服务器.MongoDB副本集提供了数据的保护.高可用和灾难恢复的机制. ...

  10. linux中Samba服务器的配置

    Samba简介 Samba是在Linux和UNIX系统上实现SMB协议的一个免费软件,由服务器及客户端程序构成.SMB(Server Messages Block,信息服务块)是一种在局域网上共享文件 ...