在这篇文章中,我们将带领您了解chapter6.3、shutil模块的使用,csv,ini,及configparser模块的全貌,包括shutil模块的功能的相关情况。同时,我们还将为您介绍有关con
在这篇文章中,我们将带领您了解chapter6.3、shutil模块的使用,csv,ini,及configparser模块的全貌,包括shutil模块的功能的相关情况。同时,我们还将为您介绍有关configparser模块-读取配置文件的模块、configparser模块简介、Configparse模块的用法、Python 2.x 中如何使用ConfigParser模块进行配置文件操作的知识,以帮助您更好地理解这个主题。
本文目录一览:- chapter6.3、shutil模块的使用,csv,ini,及configparser模块(shutil模块的功能)
- configparser模块-读取配置文件的模块
- configparser模块简介
- Configparse模块的用法
- Python 2.x 中如何使用ConfigParser模块进行配置文件操作
chapter6.3、shutil模块的使用,csv,ini,及configparser模块(shutil模块的功能)
os模块
os.name
返回操作系统平台,windows下是nt,Linux下数是posix
os,uname,Windows下不支持uname,Linux下返回posix.uname_result(sysname=‘Linux‘,nodename=‘centos‘,release=‘2.6.32-696.el6.x86_64‘,version=‘#1 SMP Tue Mar 21 19:29:05 UTC 2017‘,machine=‘x86_64‘)
sys.platform windows返回win32,linux返回linux
os.listdir ,立即返会一个目录内内容的列表
python3中鼓励使用生成器
os调用底层函数,建议使用内建函数open、read、write
os.stat(),本质调用系统功能,linux下的stat,显示文件的元信息
os.chmod,改变权限,改变权限需要权限,改权限谨慎,删文件谨慎。
linux系统操作掌握,可以看视屏学学习
shutil 高级文件操作
文件拷贝时拷贝内容,但是会丢失stat数据信息,权限等,python提供了库shutil
shutil.copy 复制file和mode
shutil.copyfileobj(fsrc,fdst[,length]) 文件对象的复制,不复制fsrc和fdst是open的打开的文件对象,复制内容,fdsr要求可写,length指定buffer的大小。
shutil.copyfile(src,dst,*,follow_symlinks=True) 复制文件内容,参数是字符类型,不含元数据,本质上就是调用copyfileobj ,所以不带元数据,二进制复制内容,比较文件的存在,和软链接判断,类型判断,follow_symlinks=True 判断软链接,True表示追进
shutil.copymode(src,follow_symlinks=True),复制权限。
shutil.copy2 拷贝文件文件的stat,mode,file,参数是字符串表示的路径
shutil.copystat 拷贝stat信息,时间信息
shutil.copytree(src,dst,symlinks=False,ignore=None,copy_function=copy2,ignore_dangling_symlinks=False)
拷贝结构树,要注意是递归复制,目标文件不能存在,ignore后是一个函数,例如
def ingnore(src,names): ignoreanmes = set() for name in names: if name.endswith(‘.py‘): ignoreanmes.add(name) return ignoreanmes shutil.copytree(‘/tmp/b‘,‘/tmp/a‘,ignore=ingnore)
表示忽略以a开头的文件,
shutil.rmtree(path,ignore_errors=False,onerror=None) 递归删除,和rm-rf 一样危险,慎用,不是原子操作,删除错误时,会中断,删除的无法还原
ignore_errors=False 表示忽略错误,为False或omitted时onerror生效,onerror为callable,接受函数function,path,execinfo
shutil.move(src,copy_function=copy2),递归移动文件和目录到目标,本身使用的是os.rename 的方法,如果不能rename,就调用copytree后删除源目录,没有确认复制完成时,不会删除源。默认使用copy2的方法。Windows下,相同盘符下改目录,不同盘符下,先复制再删除,错误时不删除源文件。
shutil还有打包功能,生成tar并压缩,支持zip、gz、bz、xz。
rar闭源的,压缩时使用zip压缩,zip是开源的。
csv文件,逗号分割值的文本文件,Comma-Separated Values。
文档位置 :http://www.ietf.org/rfc/rfc4180.txt
行列分割符分成行和列的文本文件,csv不指定编码列分割符常用,或制表符,行用\r\n
一行记录一条recode,字段可以使用双引号括起来,也可以不使用。如果字段中出现了双引号、逗号、换行符必须使用双引号括起来。如果字段的值是双引号,使用两个双引号表示一个转义。
表头可选,和字段列对齐就行。
import csv 导入csv模块,
csv.reader(iterable [,dialect=‘excel‘][optional keyword args]) 返回一个行迭代器
dialect,方言:默认使用excel方言,如下:
delimiter 列分隔符,逗号
lineterminator 行分隔符\r\n
quotechar 字段的引用符号,缺省为" 双引号
双引号的处理
doublequote 双引号的处理,默认为True。如果碰到数据中有双引号,而quotechar也是双引号,True则使用2个双引号表示,False表示使用转义字符将作为双引号的前缀
escapechar 一个转义字符,默认为None,不给抛异常
writer = csv.writer(f,doublequote=False,escapechar=‘@‘) 遇到双引号,则必须提供转义字符,此处转为@符号,如果使用转义字符,要再加一个反斜杠。
quoting 指定双引号的规则
QUOTE_ALL 所有字段
QUOTE_MINIMAL特殊字符字段,Excel方言使用该规则
QUOTE_NONNUMERIC非数字字段,加双引号
QUOTE_NONE都不使用引号。最好少用,无法对齐
excel还有一种excel_tab 方言,使用tab作为列分割符。
csv_read = reader(iterable [,dialect=‘excel‘][optional keyword args]) for x in csv_reader: print(x)
csv_writer = csv.writer(fileobj [,dialect=‘excel‘] [optional keyword args]) 返回DictWriter的实例
csv_writer.writerows(rows)
writerow,迭代每一行,用逗号分割,有歧义加引号
writerows,迭代写入表格,行尾使用\n分割,windows下在每行末尾加\n,使用newline=‘’解决。
ini 文件
配置文件,
中括号里面的部分称为section:节,区,段
每个section中都是kv对
配置文件都是文本文件,文件内都是字符类型,没有其他类型
python中要求kv对都在section中,python要求必须有第一行的缺省值
DEFAULT是缺省section的名字,必须大写,其他section没有时,default值顶上。
可以理解为嵌套字典,可以将section当做key,section存储着键值对组成的字典,可以把ini配置文件当做一个嵌套的字典。默认使用的是有序字典。
configparser模块
configparser模块的ConfigParser类就是用来操作。
可以将section当做key,section存储着键值对组成的字典,可以把ini配置文件当做一个嵌套的字典。默认使用的
是有序字典。
read(filenames,encoding=None)读取ini文件,可以是单个文件,也可以是文件列表。可以指定文件编码。
sections() 返回section列表。缺省section不包括在内。
add_section(section_name) 增加一个section。
has_section(section_name) 判断section是否存在
options(section) 返回section的所有option,会追加缺省section的option
has_option(section,option) 判断section是否存在这个option
get(section,option,raw=False,vars=None[,fallback])从指定的段的选项上取值,如果找到返回,如果没有找到就去找DEFAULT段有没有。
getint(section,fallback])
getfloat(section,fallback])
getboolean(section,fallback])
上面3个方法和get一样,返回指定类型数据。
items(raw=False,vars=None) 返回ini文件的section和sections的内容的kv对
items(section,vars=None)没有section,则返回所有section名字及其对象;如果指定section,则返回这个指定的section的键值对组成二元组。
set(section,value)
section存在的情况下,写入option=value,要求option、value必须是字符串。
remove_section(section)移除section及其所有option
remove_option(section,option)移除section下的option。
write(fileobject,space_around_delimiters=True)将当前config的所有内容写入fileobject中,一般open函数使用w模式。
configparser模块-读取配置文件的模块
ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容
创建的文件格式是cfg
文件内的格式:
[DEFAULT] # 全局的
[alex] # 用户名
Password = 123 # 密码
Quotation = 100 # 配额按MB计算
[jack]
Password = 456
Quotation = 100
二、ConfigParser 初始化对象
import configparser # 导入模块
config = configparser.ConfigParser() # 实例化对象
config.read("ini", encoding="utf-8") # 对象读取文件
三、生成文件 # 最好用程序去生成,如果手动生成则会出现编码报错
import configparser
from server.conf import settings
conf = configparser.ConfigParser()
conf.read(settings.ACCOUNT_File)
conf.add_section("alex") # 新建一个属性
conf.set("alex", "Password", "123") # 对指定的属性下生成值
conf.write(open(settings.ACCOUNT_File,''w'')) # 这里写入
config.sections() # 获取所需的section节点
config.options("db") # 获取指定section 的options
config.get("db", "db_host") # 获取指点section下指点option的值
config.getint("db", "k1") # 将获取到值转换为int型
config.getboolean("db", "k2" ) # 将获取到值转换为bool型
config.getfloat("db", "k3" ) # 将获取到值转换为浮点型
config.items("db") # 获取指点section的所用配置信息
config.set("db", "db_port", "69") # 修改某个option的值,如果不存在则会创建
config.has_section("section") # 检查是否存在该section,返回结果是bool值
config.has_option("section", "option") # 是检查section中否存在该option,返回结果是bool值
config.add_section("default") # 添加section
config.set("default", "db_host", "1.1.1.1") # 向section中添加option
config.remove_section("default") # 整个section下的所有内容都将删除
config.write(open("ini", "w")) # 增加删除新建都需要这行回写文件
configparser模块简介
[TOC]
configparser模块简介
该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。节与java原先的配置文件相同的格式
看一下configparser生成的配置文件的格式
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = Atlan
[topsecret.server.com]
Port = 50022
ForwardX11 = no
现在看一下类似上方的配置文件是如何生成的
import configparser #引入模块
config = configparser.ConfigParser() #类中一个方法 #实例化一个对象
config["DEFAULT"] = {''ServerAliveInterval'': ''45'',
''Compression'': ''yes'',
''CompressionLevel'': ''9'',
''ForwardX11'':''yes''
} #类似于操作字典的形式
config[''bitbucket.org''] = {''User'':''Atlan''} #类似于操作字典的形式
config[''topsecret.server.com''] = {''Host Port'':''50022'',''ForwardX11'':''no''}
with open(''example.ini'', ''w'') as configfile:
config.write(configfile) #将对象写入文件
解释一下,操作方式
config["DEFAULT"] = {''ServerAliveInterval'': ''45'',
''Compression'': ''yes'',
''CompressionLevel'': ''9'',
''ForwardX11'':''yes''
} #类似于操作字典的形式
#config后面跟的是一个section的名字,section的段的内容的创建类似于创建字典。类似与字典当然还有别的操作方式啦!
config[''bitbucket.org''] = {''User'':''Atlan''} #类似与最经典的字典操作方式
和字典的操作方式相比,configparser模块的操作方式,无非是在实例化的对象后面,跟一个section,在紧跟着设置section的属性(类似字典的形式)
读取文件内容
import configparser
config = configparser.ConfigParser()
#---------------------------查找文件内容,基于字典的形式
print(config.sections()) # []
config.read(''example.ini'')
print(config.sections()) # [''bitbucket.org'', ''topsecret.server.com'']
print(''bytebong.com'' in config) # False
print(''bitbucket.org'' in config) # True
print(config[''bitbucket.org'']["user"]) # Atlan
print(config[''DEFAULT''][''Compression'']) #yes
print(config[''topsecret.server.com''][''ForwardX11'']) #no
print(config[''bitbucket.org'']) #<Section: bitbucket.org>
for key in config[''bitbucket.org'']: # 注意,有default会默认default的键
print(key)
print(config.options(''bitbucket.org'')) # 同for循环,找到''bitbucket.org''下所有键
print(config.items(''bitbucket.org'')) #找到''bitbucket.org''下所有键值对
print(config.get(''bitbucket.org'',''compression'')) # yes get方法Section下的key对应的value
修改文件内容
import configparser
config = configparser.ConfigParser()
config.read(''example.ini'') #读文件
config.add_section(''yuan'') #添加section
config.remove_section(''bitbucket.org'') #删除section
config.remove_option(''topsecret.server.com'',"forwardx11") #删除一个配置想
config.set(''topsecret.server.com'',''k1'',''11111'')
config.set(''yuan'',''k2'',''22222'')
with open(''new2.ini'',''w'') as f:
config.write(f)
Configparse模块的用法
ConfigParser模块在python中是用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
注意:在python 3 中ConfigParser模块名已更名为configparser
config.read('example.ini',encoding="utf-8")
"""读取配置文件,python3可以不加encoding"""
options(section)
"""sections(): 得到所有的section,并以列表的形式返回"""
config.defaults()
"""defaults():返回一个包含实例范围默认值的词典"""
config.add_section(section)
"""添加一个新的section"""
config.has_section(section)
"""判断是否有section"""
print(config.options(section))
"""得到该section的所有option"""
has_option(section, option)
"""判断如果section和option都存在则返回True否则False"""
read_file(f, source=None)
"""读取配置文件内容,f必须是unicode"""
read_string(string, source=’’)
"""从字符串解析配置数据"""
read_dict(dictionary, source=’’)
"""从词典解析配置数据"""
get(section, option, *, raw=False, vars=None[, fallback])
"""得到section中option的值,返回为string类型"""
getint(section,option)
"""得到section中option的值,返回为int类型"""
getfloat(section,option)
"""得到section中option的值,返回为float类型"""
getboolean(section, option)
"""得到section中option的值,返回为boolean类型"""
items(raw=False, vars=None)
"""和items(section, raw=False, vars=None):列出选项的名称和值"""
set(section, option, value)
"""对section中的option进行设置"""
write(fileobject, space_around_delimiters=True)
"""将内容写入配置文件。"""
remove_option(section, option)
"""从指定section移除option"""
remove_section(section)
"""移除section"""
optionxform(option)
"""将输入文件中,或客户端代码传递的option名转化成内部结构使用的形式。默认实现返回option的小写形式;"""
readfp(fp, filename=None)
"""从文件fp中解析数据"""
生成configparser文件实例
import configparser #配置文件
config = configparser.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'
"""写入后缀为.ini的文件"""
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
读取configparser配置文件的实例
import configparser #配置文件
config = configparser.ConfigParser()
config.read("example.ini")
print("所有节点==>",config.sections())
print("包含实例范围默认值的词典==>",config.defaults())
for item in config["DEFAULT"]:
print("循环节点topsecret.server.com下所有option==>",item)
print("bitbucket.org节点下所有option的key,包括默认option==>",config.options("bitbucket.org"))
print("输出元组,包括option的key和value",config.items('bitbucket.org'))
print("bitbucket.org下user的值==>",config["bitbucket.org"]["user"]) #方式一
topsecret = config['bitbucket.org']
print("bitbucket.org下user的值==>",topsecret["user"]) #方式二
print("判断bitbucket.org节点是否存在==>",'bitbucket.org' in config)
print("获取bitbucket.org下user的值==>",config.get("bitbucket.org","user"))
print("获取option值为数字的:host port=",config.getint("topsecret.server.com","host port"))
运行结果
所有节点==> ['bitbucket.org', 'topsecret.server.com']
包含实例范围默认值的词典==> OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
循环节点topsecret.server.com下所有option==> serveraliveinterval
循环节点topsecret.server.com下所有option==> compression
循环节点topsecret.server.com下所有option==> compressionlevel
循环节点topsecret.server.com下所有option==> forwardx11
bitbucket.org节点下所有option的key,包括默认option==> ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
输出元组,包括option的key和value [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
bitbucket.org下user的值==> hg
bitbucket.org下user的值==> hg
判断bitbucket.org节点是否存在==> True
获取bitbucket.org下user的值==> hg
获取option值为数字的:host port= 50022
删除配置文件section和option的实例(默认分组有参数时无法删除,但可以先删除下面的option,再删分组)
import configparser #配置文件
config = configparser.ConfigParser()
config.read("example.ini")
config.remove_section("bitbucket.org")
"""删除分组"""
config.remove_option("topsecret.server.com","host port")
"""删除某组下面的某个值"""
config.write(open('example.ini', "w"))
运行结果
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[topsecret.server.com]
forwardx11 = no
配置文件的修改实例
"""修改"""
import configparser
config = configparser.ConfigParser()
config.read("example.ini")
config.add_section("new_section")
"""新增分组"""
config.set("DEFAULT","compressionlevel","110")
"""设置DEFAULT分组下compressionlevel的值为110"""
config.write(open('example.ini', "w"))
运行结果
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 110
forwardx11 = yes
[topsecret.server.com]
forwardx11 = no
[new_section]
Python 2.x 中如何使用ConfigParser模块进行配置文件操作
python 2.x 中如何使用 configparser 模块进行配置文件操作
一、引言
在实际的项目开发中,经常会遇到需要读取配置文件的情况。配置文件可以用来存储一些配置信息,如数据库连接信息、API密钥等。Python 中的 ConfigParser 模块提供了一个简单而强大的解决方案,可以方便地读取和修改配置文件内容。本文将介绍如何使用 ConfigParser 模块进行配置文件操作。
二、ConfigParser 模块简介
ConfigParser 模块是 Python 中用于操作 INI 文件格式的模块。INI 文件是一种常见的配置文件格式,通常由节(section)和键值对(key-value pair)组成。ConfigParser 模块提供了一些方法来读取、写入和修改配置文件内容。
三、安装 ConfigParser 模块
ConfigParser 模块是 Python 标准库的一部分,在 Python 2.x 中默认已经安装好,无需额外安装。
四、使用 ConfigParser 模块
首先,导入 ConfigParser 模块:
立即学习“Python免费学习笔记(深入)”;
import ConfigParser
下面是一种典型的 INI 文件格式:
[database] host = localhost port = 3306 username = root password = password123 [api] key = myapikey
以下是使用 ConfigParser 模块对 INI 文件进行读取的示例代码:
config = ConfigParser.ConfigParser() config.read(''config.ini'') # 获取 ''database'' 节中的 ''host'' 键的值 database_host = config.get(''database'', ''host'') print(database_host) # 输出: localhost # 获取 ''api'' 节中的 ''key'' 键的值 api_key = config.get(''api'', ''key'') print(api_key) # 输出: myapikey
config.get(section, option) 方法用于获取指定节(section)中指定键(option)的值。
以上的代码示例中,我们首先创建了一个 ConfigParser 对象 config,然后使用 config.read(''config.ini'') 方法读取配置文件。接下来,可以使用 config.get() 方法来获取各个节中的键值。
如果配置文件中的键不存在,或者节不存在,那么 config.get() 方法将抛出 ConfigParser.Error 异常。我们可以使用 config.has_option() 和 config.has_section() 方法来检查键或节是否存在,从而避免异常的出现。
以下是使用 ConfigParser 模块对 INI 文件进行修改的示例代码:
config = ConfigParser.ConfigParser() config.read(''config.ini'') # 修改 ''database'' 节中的 ''host'' 键的值 config.set(''database'', ''host'', ''newhost'') # 添加新的节和键值对 config.add_section(''new_section'') config.set(''new_section'', ''new_option'', ''value'') # 保存修改后的配置文件 with open(''config.ini'', ''w'') as f: config.write(f)
config.set(section, option, value) 方法用于修改配置文件中指定键的值,config.add_section(section) 方法用于添加新的节,config.write(file) 方法用于将修改后的配置文件写入磁盘。
五、总结
ConfigParser 模块提供了一种方便的方式来读取、写入和修改 INI 格式的配置文件。通过简单的 API 调用,可以轻松地进行配置文件操作。在实际的项目开发中,使用 ConfigParser 模块可以有效地管理配置信息,提高代码的可扩展性和维护性。
本文介绍了 ConfigParser 模块的基本用法和常见操作,包括读取配置文件和修改配置文件。希望本文能为读者提供一个简单而实用的方法来处理配置文件,在实际的开发工作中有所帮助。
更多关于 ConfigParser 模块的详细信息,请参考 Python 官方文档:https://docs.python.org/2/library/configparser.html
以上就是Python 2.x 中如何使用ConfigParser模块进行配置文件操作的详细内容,更多请关注php中文网其它相关文章!
我们今天的关于chapter6.3、shutil模块的使用,csv,ini,及configparser模块和shutil模块的功能的分享已经告一段落,感谢您的关注,如果您想了解更多关于configparser模块-读取配置文件的模块、configparser模块简介、Configparse模块的用法、Python 2.x 中如何使用ConfigParser模块进行配置文件操作的相关信息,请在本站查询。
本文标签: