Python--day5--常用模块
介绍:
本文主要是学习python常用模块的记录,后面记录的不是很详细,以后再补。
2016年12月27日
目录:
模块介绍
json & pickle
time & datetime模块 &月历
random模块
OS
SYS
shutil
shelves
xml
yaml
ConfigParser
hashlib
subprocess
logging
模块
就是用一堆代码实现某个功能的代码集合。
模块分三种:
自定义模块
内置标准模块(标准库)
开源模块
开源模块网站 : pypi.python.org
调用模块
调用
from backend.logic import handle ##这样导入目录必须是包的状态,也就是包下面 有一个 __init__.py
handle.home()
sql.py
import sys
import os.path
base_dir=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) ##获得目录
sys.path.append(base_dir) ##修改库的目录
from config import settings
def db_auth(configs):if configs.DATABASE["user"] == 'root' and configs.DATABASE["password"] == "123":print("OK")return Trueelse:print("error")
def s(table,column):if db_auth(settings):if table == 'user':user_info = {"001":['hequan',24,'engineer'],"002":['he123', 44, 'beijing'],"003":['he456', 55, 'hebei'],}return user_infoelse:print("cuowu.......")
handle.py
import sys
import os.path
base_dir=os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(base_dir)
from back.db.sql import s
def home():print("welcome to home page")q_data = s("user",'xxx')print("query res: {}".format(q_data))
def movie():print("welcome to movie page")
def tv():print("welcome to tv page")
settings.py
DATABASE ={"engine":"mysql","host":"localhost","port":3306,"user":"root","password":"123",
}
user_main.py
from back.logic import handle
handle.home()
结果
welcome to home page
OK
query res: {'003': ['he456', 55, 'hebei'], '001': ['hequan', 24, 'engineer'], '002': ['he123', 44, 'beijing']}
json&pickle 序列化
json 用于字符串和python数据类型间进行转化 r w
pickle 用于python特有的类型和python的数据类型间进行转换 rb wb 支持更复杂的调用函数
都提供了4个功能: dumps\dump\loads\load
例子
pickle写入
import pickle
f =open("user.txt","wb") ##json 只是w
info={"user":"123","hequan":'123'
}
f.write(pickle.dumps(info))
f.close()读取
import pickle
f= open("user.txt",'rb')
data =pickle.loads(f.read())
print(data)
dumps 与 dump的 区别
pickle.dump(info,f) ##写入
data =pickle.load(f) ##读取
time
import time
时间元祖
序号 | 字段 | 值 |
---|---|---|
0 | 4位数年 tm_year | 2008 |
1 | 月 tm_mon | 1 到 12 |
2 | 日 tm_day | 1到31 |
3 | 小时 tm_hour | 0到23 |
4 | 分钟 tm_min | 0到59 |
5 | 秒 tm_sec | 0到61 (60或61 是闰秒) |
6 | 一周的第几日 tm_wday | 0到6 (0是周一) |
7 | 一年的第几日 tm_yday | 1到366 (儒略历) |
8 | 夏令时 tm_isdst | -1, 0, 1, -1是决定是否为夏令时的旗帜 |
获取当前时间
import time
localtime = time.localtime(time.time())
print(localtime)
time.struct_time(tm_year=2016, tm_mon=12, tm_mday=27, tm_hour=16, tm_min=46, tm_sec=44, tm_wday=1, tm_yday=362, tm_isdst=0)获取格式化时间
localtime = time.asctime(time.localtime(time.time()))
print(localtime)
Tue Dec 27 16:47:56 2016格式化日期
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
2016-12-27 16:49:16月历
import calendar
cat = calendar.month(2017,1)
print(cat)January 2017
Mo Tu We Th Fr Sa Su12 3 4 5 6 7 89 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31datetimeimport datetime
date = datetime.datetime.now()
print(date)
2016-12-27 16:54:42.472913
random模块
随机数
random.randint(a, b), 用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
random.randrange([start], stop[, step]) 从指定范围内,按指定基数递增的集合中 获取一个随机数。如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, ... 96, 98]序列中获取一个随机数。
os模块
os.popen("dir").read() 执行命令,暂时保存到一个地方
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir(
"dirname"
) 改变当前脚本工作目录;相当于shell下cd
os.curdir 返回当前目录: (
'.'
)
os.pardir 获取当前目录的父目录字符串名:(
'..'
)
os.makedirs(
'dirname1/dirname2'
) 可生成多层递归目录
os.removedirs(
'dirname1'
) 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir(
'dirname'
) 生成单级目录;相当于shell中mkdir dirname
os.rmdir(
'dirname'
) 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir(
'dirname'
) 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename(
"oldname"
,
"newname"
) 重命名文件
/
目录
os.stat(
'path/filename'
) 获取文件
/
目录信息
os.sep 输出操作系统特定的路径分隔符,win下为
"\\",Linux下为"
/
"
os.linesep 输出当前平台使用的行终止符,win下为
"\t\n"
,Linux下为
"\n"
os.pathsep 输出用于分割文件路径的字符串
os.name 输出字符串指示当前使用平台。win
-
>
'nt'
; Linux
-
>
'posix'
os.system(
"bash command"
) 运行shell命令,直接显示
os.environ 获取系统环境变量
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回
True
;如果path不存在,返回
False
os.path.isabs(path) 如果path是绝对路径,返回
True
os.path.isfile(path) 如果path是一个存在的文件,返回
True
。否则返回
False
os.path.isdir(path) 如果path是一个存在的目录,则返回
True
。否则返回
False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
SYS模块
sys.argv 命令行参数
List
,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(
0
)
sys.version 获取Python解释程序的版本信息
sys.maxint 最大的
Int
值
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操作系统平台名称
sys.stdout.write(
'please:'
)
val
=
sys.stdin.readline()[:
-
1
]
shutil 文件 文件夹 处理模块
shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中,可以部分内容
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
shutil.copyfile(src, dst)
拷贝文件
shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变
shutil.copystat(src, dst)
拷贝状态的信息,包括:mode bits, atime, mtime, flags
shutil.copy(src, dst)
拷贝文件和权限
shutil.copy2(src, dst)
拷贝文件和状态信息
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件
例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件
shutil.move(src, dst)
递归的去移动文件
shutil.make_archive(base_name, format,...)
创建压缩包并返回文件路径,例如:zip、tar
base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
如:www =>保存至当前路径
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
root_dir: 要压缩的文件夹路径(默认当前目录)
owner: 用户,默认当前用户
group: 组,默认当前组
logger: 用于记录日志,通常是logging.Logger对象
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的
shelve
是一个简单的k,v 将内存数据通过文件持久化的模块,支持pickle
import shelve
d = shelve.open('shelve_test') #打开一个文件
class Test(object):
def __init__(self,n):
self.n = n
t = Test(123)
t2 = Test(123334)
name = ["alex","rain","test"]
d["test"] = name #持久化列表
d["t1"] = t #持久化类
d["t2"] = t2
d.close()
xml模块
实现不同语言或程序直接进行数据交换 <>
yaml
http://pyyaml.org/wiki/PyYAMLDocumentation
configparser模块
用于生成和修改常见配置文档。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45','Compression': 'yes','CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:config.write(configfile)
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
host port = 50022
forwardx11 = no
hashlib模块
加密操作
subprocess模块
logging
提供了标准的日志接口。
分5个级别
debug() info() warning() error() critical()
import logginglogging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down")#输出
WARNING:root:user [alex] attempted wrong password more than 3 times
CRITICAL:root:server is downimport logginglogging.basicConfig(filename='example.log',level=logging.INFO)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
转载于:https://blog.51cto.com/hequan/1886646
Python--day5--常用模块相关推荐
- 数据采集与清洗基础习题(二)Python爬虫常用模块,头歌参考答案
数据采集习题参考答案,会持续更新,点个关注防丢失.为了方便查找,已按照头歌重新排版,朋友们按照头歌所属门类查找实训哦,该篇为Python爬虫常用模块. 创作不易,一键三连给博主一个支持呗. 文章目录 ...
- Python自学——python的常用模块
Python学习--python的常用模块 原文作者:佛山小程序员 原文链接:https://blog.csdn.net/weixin_44192923/article/details/8656325 ...
- 【Python】常用模块安装命令
[Python]常用模块安装命令 Python常用模块安装命令 pylab模块 No module named 'apkutils' No module named 'win32api' Python ...
- 数据分析的基础:前言、概念、应用、分析方法、分析工具、基本流程、Python数据分析常用模块
文章目录 一.前言 1.数据价值 2.数据分析之路 二.数据分析的概念 三.数据分析的应用 四.数据分析方法 1.概念 2.详解 五.数据分析工具 六.数据分析的基本流程 七.Python数据分析常用 ...
- Python的常用模块
目录: time模块 random()模块 os模块 sys模块 Json模块 hashlib 模块 subprocess模块 paramiko模块 re模块 time模块 time()模块中的重要函 ...
- Python学习 - 常用模块(二)
目录 一. 常用模块 - hashlib 二. 常用模块 - hmac 三. 常用模块 - logging 四. 常用模块 - re 五. 常用模块 - requests 六. 常用模块 - para ...
- python的常用函数模块_(5)Python的常用模块函数
python 的常用系统函数,random模块函数,time模块函数和calendar模块函数. 1 random模块函数. 随机数种字,使用seed(x)函数可以设置随机数生成器的种子,通常在调用其 ...
- python自动化常用模块_Python自动化之常用模块
1 time和datetime模块 #_*_coding:utf-8_*_ __author__ = 'Alex Li' import time # print(time.clock()) #返回处理 ...
- python colorama_Python常用模块—— Colorama模块
简介 Python的Colorama模块,可以跨多终端,显示字体不同的颜色和背景,只需要导入colorama模块即可,不用再每次都像linux一样指定颜色. 1. 安装colorama模块 pip i ...
- 【Python】常用模块(三)——collections模块中的几个常用方法详解
前言 本篇博客主要就少Python常用模块collections中的几个常用方法,作为一种更高级的数据结构,这个模块提供了几个高效的方法来处理数据. Counter Counter用于统计元素个数,具 ...
最新文章
- .Net Core MVC初学习
- SAP MM 如何查询物料凭证号是由哪个IDoc Post后产生的?
- python基础-字典
- 题目1550:分糖果
- 通信基站(dfs回溯,思维)
- 浏览器打开php显示空白,pc微信浏览器打开页面显示空白,其他浏览器正常
- JAVA代码实现按列表中元素的时间字段排序
- python batch_size_python 實現動態 batch size,多張圖片如何堆疊轉成指針
- 前端学习(2754):配置tabber
- entity framework6 edmx文件详解
- 线程Blocked--SynchronizedDemo
- 拼多多协助广东警方打击网络黑灰产 15名嫌疑人于近日落网
- 组装电脑多少钱一台_客户花9000元组装一台电脑,奸商赚5000块,利润真吓人
- 【兼容写法】HttpServerUtility.Execute 在等待异步操作完成时被阻止。关键词:MVC,分部视图,异步...
- Linux学习笔记——SecureCRT 8版本中文破解版
- python批量处理照片为可打印的黑底白字图片
- Explain语法(精)
- 台式计算机默认关机变注销,Win7电脑点关机变成注销怎么办?
- 单位dB(分贝)的含义和好处,dBm(dBmW 分贝毫瓦)的含义
- python - 输入某年某月某日,判断这一天是这一年的第几天?
热门文章
- 大学生创业难?现在已不是问题!
- python多功能电子钟_python gui - PyQt4 精彩实例分析之电子钟
- 澳洲计算机学,2020年澳洲计算机科学专业工作好找吗
- mybatis-plus对datetime返回去掉.0_华为AI认证-TensorFlow2.0编程基础
- java transient关键字_小伙子,你真的搞懂 transient 关键字了吗?
- Java学习总结:46(内存流)
- 微信小程序如何进行登录授权和获取用户信息
- 带无线网卡的电脑开启热点
- Block 底层值__Block修饰符
- TinyCrayon-iOS-SDK:强大到使人惊讶的 Mask 及切图工具库