一、shutil
shutil提供对高级的 文件、文件夹、压缩包的处理
1、shutil.copyfileobj(fsrc, fdst[, length])将文件内容拷贝到另一个文件中
import shutil
shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
2、shutil.copyfile(src, dst)拷贝文件
shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在
3、shutil.copymode(src, dst)仅拷贝权限。内容、组、用户均不变
shutil.copymode('f1.log', 'f2.log') #目标文件必须存在
4、shutil.copystat(src, dst)仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
shutil.copystat('f1.log', 'f2.log') #目标文件必须存在
5、shutil.copy(src, dst)拷贝文件和权限
shutil.copy('f1.log', 'f2.log')
6、shutil.copy2(src, dst)拷贝文件和状态信息
shutil.copy2('f1.log', 'f2.log')
7、shutil.ignore_patterns(*patterns)、shutil.copytree(src, dst, symlinks=False, ignore=None)递归的去拷贝文件夹
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除
8、shutil.rmtree(path[, ignore_errors[, onerror]])递归的去删除文件
shutil.rmtree('folder1')
9、shutil.move(src, dst)递归的去移动文件,它类似mv命令,其实就是重命名。
shutil.move('folder1', 'folder3')
10、shutil.make_archive(base_name, format,...) 创建压缩包并返回文件路径,例如:zip、tar
- base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
如 data_bak =>保存至当前路径
如:/tmp/data_bak =>保存至/tmp/ - format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
- root_dir: 要压缩的文件夹路径(默认当前目录)
- owner: 用户,默认当前用户
- group: 组,默认当前组
- logger: 用于记录日志,通常是logging.Logger对象
#将 /data 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
#将 /data下的文件打包放置 /tmp/目录
import shutil
ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:
zipfile压缩&解压缩
import zipfile
# 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()
# 解压
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall(path='.')
z.close()
tarfile压缩&解压缩
import tarfile
# 压缩
>>> t=tarfile.open('/tmp/egon.tar','w')
>>> t.add('/test1/a.py',arcname='a.bak')
>>> t.add('/test1/b.py',arcname='b.bak')
>>> t.close()
# 解压
>>> t=tarfile.open('/tmp/egon.tar','r')
>>> t.extractall('/egon')
>>> t.close()
二、ConfigParser
此模块用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。
假如有一个example.ini的文件,内容如下:
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes[bitbucket.org]
User = hg[topsecret.server.com]
Port = 50022
ForwardX11 = no
>>> import configparser # 导入模块
>>> config = configparser.ConfigParser() #实例化(生成对象)
>>> config.sections() #调用sections方法
[]
>>> config.read('example.ini') # 读配置文件(注意文件路径)
['example.ini']
>>> config.sections() #调用sections方法(默认不会读取default)
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config #判断元素是否在sections列表内
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User'] # 通过字典的形式取值
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key) # for循环 bitbucket.org 字典的key
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'
其它增删改查语法
i.cfg文件如下
[group1] # 支持的两种分隔符“=”, “:”
k1 = v1
k2:v2[group2]
k1 = v1
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('i.cfg')
# ########## 读 ##########
secs = config.sections()
print(secs)
options = config.options('group2') # 获取指定section的keys
print(options)
item_list = config.items('group2') # 获取指定 section 的 keys & values ,key value 以元组的形式
print(item_list)
val = config.get('group1','key') # 获取指定的key 的value
val = config.getint('group1','key')
# ########## 改写 ##########
sec = config.remove_section('group1') # 删除section 并返回状态(true, false)
config.write(open('i.cfg', "w")) # 对应的删除操作要写入文件才会生效
sec = config.has_section('wupeiqi')
sec = config.add_section('wupeiqi')
config.write(open('i.cfg', "w")) #
config.set('group2','k1',11111)
config.write(open('i.cfg', "w"))
config.remove_option('group2','age')
config.write(open('i.cfg', "w"))