h3

php程序员学习python3学习第十三天

1,configparser 读取配置文件,操作配置文件

# -*- coding: utf-8 -*-
#配置文件模块
'''
配置文件格式,这种格式才可以使用此模块进行读取
[people]
age = 123
gender = 0
[area]
pro = beijing
city = beijing
'''
import configparser
con = configparser.ConfigParser()
#con对象的read功能是打开文件读取文件,内容放到对象中
con.read('config1.py', encoding = 'utf-8')
#获取所有的节点
res = con.sections()
print(res)
#获取指定节点的所有的key
ret = con.options("people")
print(ret)
#获取指定节点中指定键的值
'''
get() 获取到的值都为字符串
getint() 获取到整型值
getfloat() 获取到浮点型值
getboolean() 获取到布尔值
'''
str1 = con.get('people', 'age')
print(str1, type(str1))
int1 = con.getint('people', 'age')
print(int1,type(int1))
float1 = con.getfloat('people', 'age')
print(float1, type(float1))
boolean1 = con.getboolean('people', 'gender')
print(boolean1, type(boolean1))
print(dir(con))
#检查
has_sec = con.has_section('people')
print(has_sec)
#添加节点
# con.add_section('hobby1')
# con.write(open('config1.py', 'w'))
#删除节点
# con.remove_section('hobby')
# con.write(open('config1.py', 'w'))

#检查,删除,设置指定组内的键值对

#检查
has_opt = con.has_option('people', 'age')
print(has_opt)

#设置
# con.set('people', 'work1', 'eat')
# con.write(open('config1.py',  'w'))

#删除
# con.remove_option('people','work')
# con.write(open('config1.py', 'w'))
View Code

2,shutil 文件,文件夹,压缩包处理模块 zipflie tarfile zip压缩包,tar压缩包处理模块

# -*- coding: utf-8 -*-
#高级的文件,文件夹,压缩包 处理模块
'''
shutil.copyfileobj() 将文件内容拷贝到另一个文件夹中
shutil.copyfile() 拷贝文件
shutil.copymode() 仅拷贝权限,组,用户不变
shutil.coptstat() 拷贝状态的信息 包括 mode bites, atime, mtime, flags
shutil.copy() 拷贝文件和权限

shutil.copttree() 递归的拷贝文件夹
shutil.rmtree() 递归的删除文件夹
shutile.move() 递归的移动文件夹

shutil.make_archive(base_name, format) 创建压缩包并返回文件路径 例如zip,tar
base_name 压缩包的文件名,也可以是压缩包的路径,只是文件名时保存到当前目录,否则保存至指定路径
format 压缩包种类 zip,tar,bztar,gztar
root_dir 要压缩的文件路径,默认为当前目录
'''

import shutil
# shutil.copyfileobj(open('config1.py', 'r'), open('new.py', 'w'))
shutil.copyfileobj(open('config1.py', 'r'), open('new.py', 'a'))

shutil.copyfile('config1.py', 'new1.py')

shutil.copymode('config1.py', 'new1.py')

# ignore = shutil.ignore_patterns('*.pyc', 'tmp*') 设定指定文件不拷贝
# shutil.copytree('../day2', 'day2copy', ignore = shutil.ignore_patterns('*.pyc', 'tmp*'))

#递归的删除文件夹
# shutil.rmtree('day2copy')

#递归的移动文件夹
# shutil.move('day2copy','day2copy_move')

#将指定文件夹压缩为压缩包
ret = shutil.make_archive('aaaaaa', 'gztar', root_dir = './day2copy_move')
print(ret)

#zipfile模块,压缩文件,可以将单个文件压缩进去或者解压
import zipfile
#压缩
# z = zipfile.ZipFile('bbbb.zip', 'w') #创建一个压缩包
# z.write('config1.py') #将文件压缩进去
# z.write('new.py')
# z.close()

#解压
z = zipfile.ZipFile('bbbb.zip', 'r')
z.extractall() #解压所有文件
# z.extract('xxx') #解压指定文件
z.close()

#tarfile 对tar包进行压缩解压
import tarfile
#压缩
# tar = tarfile.open('my.tar', 'w')
# tar.add('new.py',arcname =  'newtar.py') #arcname 可以将压缩进去的内容进行替换名字
# tar.close()
#解压
tar = tarfile.open('my.tar', 'r')
tar.extractall()
tar.close()

3,

posted @ 2017-06-06 23:07  码上平天下  阅读(83)  评论(0)    收藏  举报