Python 模块续和面向对象的介绍(六)
一、基本模块
shutil
文件、目录、压缩包的处理模块
shutil.copyfile(src, dst)
拷贝文件 >>> shutil.copyfile('a.log','b.log')
‘b.log'
-rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log
-rw-r--r-- 1 jack wheel 4 2 25 16:03 b.log
shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变 >>> shutil.copymode('a.log','b.log’)
jackdeMacBook-Pro:python jack$ ll total 16 -rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log -rwxr-xr-x 1 jack wheel 4 2 25 16:03 b.log* jackdeMacBook-Pro:python jack$ ll total 16 -rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log -rw-r--r-- 1 jack wheel 4 2 25 16:03 b.log
shutil.copystat(src, dst)
拷贝状态的信息,包括:mode bits, atime, mtime, flags >>> shutil.copystat('a.log','b.log')
jackdeMacBook-Pro:python jack$ stat a.log
16777220 6143218 -rw-r--r-- 1 jack wheel 0 4 "Feb 25 16:03:07 2016" "Feb 25 15:59:52 2016" "Feb 25 15:59:52 2016" "Feb 25 15:59:52 2016" 4096 8 0 a.log
jackdeMacBook-Pro:python jack$ stat b.log
16777220 6143570 -rw-r--r-- 1 jack wheel 0 4 "Feb 25 16:03:07 2016" "Feb 25 16:03:07 2016" "Feb 25 16:06:11 2016" "Feb 25 16:03:07 2016" 4096 8 0 b.log
jackdeMacBook-Pro:python jack$ stat b.log
16777220 6143570 -rw-r--r-- 1 jack wheel 0 4 "Feb 25 16:03:07 2016" "Feb 25 15:59:52 2016" "Feb 25 16:07:28 2016" "Feb 25 15:59:52 2016" 4096 8 0 b.log
shutil.copy(src, dst)
拷贝文件和权限 >>> shutil.copy('a.log','b.log')
‘b.log'
jackdeMacBook-Pro:python jack$ ll
total 16
-rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log
-rwxr-xr-x 1 jack wheel 11 2 25 16:09 b.log*
jackdeMacBook-Pro:python jack$ ll
total 16
-rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log
-rw-r--r-- 1 jack wheel 4 2 25 16:09 b.log
shutil.copy2(src, dst)
拷贝文件和状态信息 >>> shutil.copy2('a.log','c.log’)
‘c.log'
-rw-r--r-- 1 jack wheel 4 2 25 15:59 a.log
-rw-r--r-- 1 jack wheel 4 2 25 16:09 b.log
-rw-r--r-- 1 jack wheel 4 2 25 15:59 c.log
jackdeMacBook-Pro:python jack$ stat a.log
16777220 6143218 -rw-r--r-- 1 jack wheel 0 4 "Feb 25 16:11:26 2016" "Feb 25 15:59:52 2016" "Feb 25 15:59:52 2016" "Feb 25 15:59:52 2016" 4096 8 0 a.log
jackdeMacBook-Pro:python jack$ stat c.log
16777220 6144432 -rw-r--r-- 1 jack wheel 0 4 "Feb 25 16:11:26 2016" "Feb 25 15:59:52 2016" "Feb 25 16:11:26 2016" "Feb 25 15:59:52 2016" 4096 8 0 c.log
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件
>>> shutil.copytree('a','b')
‘b'
jackdeMacBook-Pro:python jack$ tree
└── a
└── a.log jackdeMacBook-Pro:python jack$ tree
├── a
│ └── a.log
└── b
└── a.log
shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件 >>> shutil.rmtree('b’)
drwxr-xr-x 3 jack wheel 102 2 25 16:13 a/
shutil.move(src, dst)
递归的去移动文件 >>> shutil.move('a','c’)
‘c'
drwxr-xr-x 3 jack wheel 102 2 25 16:13 c/
import shutil #指定压缩后的文件名/压缩方法/源路径
ret = shutil.make_archive('test','zip',root_dir='/Users/jack/Documents/git/github/Demo/days06/test')
#指定压缩后的目标路径和文件名/压缩方法/源路径
ret = shutil.make_archive('/Users/jack/Documents/git/github/Demo/days06/ss','zip',root_dir='/Users/jack/Documents/git/github/Demo/days06/test') #区别 压缩后放置当前程序目录 #解压
import zipfile
z = zipfile.ZipFile('test.zip','r')
z.extractall()
z.close()
xml处理模块
import xml.etree.ElementTree as et
tree = et.parse('t1.xml')
root = tree.getroot()
#print(root.tag)
#遍历整个文档
'''
for child in root:
print(child.tag,child.attrib)
for i in child:
print(i.tag,i.text)
'''
#遍历rank节点
'''
for node in root.iter('rank'):
print(node.tag,node.text)
'''
'''
#修改节点
for node in root.iter('rank'):
print(node.tag,node.text)
new_rank = int(node.text) + 10
node.text = str(new_rank)
node.set('update','sss')
tree.write('t2.xml')
'''
#删除节点
'''
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 60 :
root.remove(country)
tree.write('t3.xml')
'''
'''
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {
'ServerAliveInterval':'45',
'Compression':'yes',
'ComressionLevel':'9'
}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topSecret.server.com'] = {}
topSecret = config['topSecret.server.com']
topSecret['Host Port'] = '3306'
topSecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardXll'] = 'yes'
with open('ss1.cfg','w') as configfile:
config.write(configfile)
configparser
用于对特定的配置进行操作
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('ss1.cfg')
['ss1.cfg']
>>> config.sections()
['bitbucket.org', 'topSecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bitbucket.orgs' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topSecret.server.com']
>>> topsecret['host port']
'' >>> for key in config['bitbucket.org']:print(key)
...
user
compression
serveraliveinterval
comressionlevel
forwardxll
>>> config['bitbucket.org']['forwardxll']
'yes' hashlib
import hashlib h = hashlib.md5()
h.update(b'haha')
h.update(b'enenen') msg = h.digest()
msg1 = h.hexdigest()
print(msg)
>>> print(msg)
b'b\xfc\xb2\xd9\x07\x83\x81\x18I\x1a\x0c\xaf\xa6\xdb\xbf\xd7'
>>> print(msg1)
62fcb2d907838118491a0cafa6dbbfd7
subprocess
>>> import subprocess as sub
>>> sub.run('df')
Filesystem 512-blocks Used Available Capacity iused ifree %iused Mounted on
/dev/disk1 234586112 138600696 95473416 60% 17389085 11934177 59% /
devfs 371 371 0 100% 642 0 100% /dev
map -hosts 0 0 0 100% 0 0 100% /net
map auto_home 0 0 0 100% 0 0 100% /home
/dev/disk2s1 253425664 37116928 216308736 15% 144988 844956 15% /Volumes/Backup
CompletedProcess(args='df', returncode=0)
>>>sub.run(['df -h'],shell=True)
Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
/dev/disk1 112Gi 66Gi 46Gi 60% 17389072 11934190 59% /
devfs 186Ki 186Ki 0Bi 100% 642 0 100% /dev
map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net
map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home
/dev/disk2s1 121Gi 18Gi 103Gi 15% 144988 844956 15% /Volumes/Backup
CompletedProcess(args=['df -h'], returncode=0)
>>> sub.run(['df -h'],shell=True,stdout=subprocess.PIPE)
CompletedProcess(args=['df -h'], returncode=0, stdout=b'Filesystem Size Used Avail Capacity iused ifree %iused Mounted on\n/dev/disk1 112Gi 66Gi 46Gi 60% 17389258 11934004 59% /\ndevfs 186Ki 186Ki 0Bi 100% 642 0 100% /dev\nmap -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net\nmap auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /home\n/dev/disk2s1 121Gi 18Gi 103Gi 15% 144988 844956 15% /Volumes/Backup\n')
logging
用于便捷记录日志且线程安全的模块
日志可以分为 debug(), info(), warning(), error() and critical() 5个级别
import logging
logging.debug('this is a debug messages!')
logging.info('this is a info messages!')
logging.warning('this is a warning messages!')
logging.critical('this is a critical messages!!!')
logging.basicConfig(format='%(asctime)s %(message)s',datefmt='%Y-%m-%d %H:%M',filename='access.log',level=logging.INFO)
logging.debug('This messages should go to the access.log!')
logging.info('This is info!')
logging.warning('This is warning')
logger = logging.getLogger('Test')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
fh = logging.FileHandler('access.log')
fh.setLevel(logging.WARNING)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
logger.addHandler(ch)
logger.addHandler(fh)
logger.debug('debug')
logger.info('info..')
logger.warn('warn!')
logger.error('error!!')
logger.critical('critical!!!')
二、初识面向对象
什么是类?
动物、人、山等都是类。
什么是对象?
对象即类的实体,小明就是对象。
什么是方法?
定义一个类的功能,小明会吃饭就是方法。
什么是继承?
继承父类,小明也有黑色的头发.
什么是封装?
小明不能像袋鼠一样蹦。
什么是多态性?
拍一巴掌,可能是很大的力气,也可能是很温柔的。
什么是抽象性?
简化复杂的现实的问题途径,可以给任何问题找到恰当的类的定义,比如空气。
类就是一个模板,模板里包括很多函数,函数可以实现很多功能。对象就是根据模板创建的实例,通过实例化对象可以执行类里面的函数。
如何定义一个类?
类是对现实世界中一些事物的封装,可以用下面的方式来定义:
class Role(object):
block
在block里面就可以定义属性和方法。定义完类后,就产生一个类对象。类对象支持引用和实例化。引用是通过类对象去调用类中的属性或者方法。而实例化是产生出一个类对象的实例,称作实力对象。
由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。通过定义一个特殊的__init__方法,在创建实例的时候,就把life_value等属性绑上去:
class Role(object):
def __init__(self,name,armor,weapon,life_value=100,money=0):
self.name = name
self.armor = armor
self.weapon = weapon
self.life_value = life_value
self.money = money
和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self,并且,调用时,不用传递该参数。除此之外,类的方法和普通函数没有什么区别,所以,你仍然可以用默认参数、可变参数、关键字参数和命名关键字参数。
class Role(object):
def __init__(self,name,armor,weapon,life_value=100,money=0):
self.name = name
self.armor = armor
self.weapon = weapon
self.life_value = life_value
self.money = money
def damage(self):
pass
Python 模块续和面向对象的介绍(六)的更多相关文章
- Python开发基础-Day17面向对象编程介绍、类和对象
面向对象变成介绍 面向过程编程 核心是过程(流水线式思维),过程即解决问题的步骤,面向过程的设计就好比精心设计好一条流水线,考虑周全什么时候处理什么东西.主要应用在一旦完成很少修改的地方,如linux ...
- Python 模块续 configparser、shutil、XML、paramiko、系统命令、
一.configparse # 注释1 ; 注释2 [section1] # 节点 k1 = v1 # 值 k2:v2 # 值 [section2] # 节点 k1 = v1 # 值 1.获取所有节点 ...
- python模块之datetime方法详细介绍
datetime Python提供了许多内置模块用于操作时间日期,如calendar,time,datetime,这篇文章主要是对datetime进行汇总,datetime模块的借口实现原则更加直观, ...
- python模块之calendar方法详细介绍
calendar,是与日历相关的模块.calendar模块文件里定义了很多类型,主要有Calendar,TextCalendar以及HTMLCalendar类型.其中,Calendar是TextCal ...
- python(23)- 面向对象简单介绍
面向概述 面向过程:根据业务逻辑从上到下写垒代码 面向过程的设计的核心是过程,过程即解决问题的步骤, 面向过程的设计就好比精心设计好一条流水线,考虑周全什么时候处理什么东西 优点:极大降低了程序的复杂 ...
- python模块之time方法详细介绍
>>> import time >>> dir(time) ['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__nam ...
- python 模块加载
python 模块加载 本文主要介绍python模块加载的过程. module的组成 所有的module都是由对象和对象之间的关系组成. type和object python中所有的东西都是对象,分为 ...
- 详解Python模块导入方法
python常被昵称为胶水语言,它能很轻松的把用其他语言制作的各种模块(尤其是C/C++)轻松联结在一起.python包含子目录中的模块方法比较简单,关键是能够在sys.path里面找到通向模块文件的 ...
- Python模块的介绍
Python模块的学习: 1.os模块: 下面只对os模块中几个比较常用的方法做一些简单的示例: os.system():这个方法在shell中体现的比较多,在dos命令行中也可以执行,下面就以在do ...
随机推荐
- jmeter 通过ant集成到jenkins
jmeter可以通过ant自动执行测试脚本,然后集成到jenkins上,并发送测试报告 1.下载安装ant 2.将jmeter安装包extras文件夹里ant-jemter-1.1.1.jar 复制到 ...
- UUID Gen
https://github.com/twitter/snowflake/releases/tag/snowflake-2010 http://boundary.com/blog/2012/01/12 ...
- WINDOWS硬件通知应用程序的常方法
摘要:在目前流行的Windows操作系统中,设备驱动程序是操纵硬件的最底层软件接口.为了共享在设备驱动程序设计过程中的经验,给出设备驱动程序通知应用程序的5种方法,详细说明每种方法的原理和实现过程,并 ...
- python+opencv
$cd numpy $ sudo python setup.py build $ sudo python setup.py installRunning from numpy source direc ...
- linux 多线程编程笔记
一, 线程基础知识 1,线程的概念 线程是进程的一个实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位.线程自己基本上不拥有系统资源,只拥有一点在运行 中必不可少的资源(如程序计 ...
- 如何设计一个 iOS 控件?(iOS 控件完全解析)
前言 一个控件从外在特征来说,主要是封装这几点: 交互方式 显示样式 数据使用 对外在特征的封装,能让我们在多种环境下达到 PM 对产品的要求,并且提到代码复用率,使维护工作保持在一个相对较小的范围内 ...
- YUV / RGB 格式及快速转换算法
1 前言 自然界的颜色千变万化,为了给颜色一个量化的衡量标准,就需要建立色彩空间模型来描述各种各样的颜色,由于人对色彩的感知是一个复杂的生理和心理联合作用 的过程,所以在不同的应用领域中为了更好更准确 ...
- sql 时间和字符串 取到毫秒级
(select replace(replace(replace(CONVERT(varchar, getdate(), 120 ),'-',''),' ',''),':','')+(Select ri ...
- java结构与算法之选择排序
一 .java结构与算法之选择排序(冒择路兮快归堆) 什么事选择排序:从一组无序数据中选择出中小的的值,将该值与无序区的最左边的的值进行交换. 简单的解释:假设有这样一组数据 12,4,23,5,找到 ...
- spring和mybatis整合进行事务管理
1.声明式实现事务管理 XML命名空间定义,定义用于事务支持的tx命名空间和AOP支持的aop命名空间: <beans xmlns="http://www.springframewor ...