Ⅰ 如何使用Python3讀寫INI配置文件
ini文件簡介
ini是我們常見到的配置文件格式之一。
ini是微軟Windows操作系統中的文件擴展名(也常用在其他系統)。
INI是英文「初始化(Initial)」的縮寫。正如該術語所表示的,INI文件被用來對操作系統或特定程序初始化或進行參數設置。
網路
通過它,可以將經常需要改變的參數保存起來(而且還可讀),使程序更加的靈活。
我先給出一個ini文件的示例。
[School]
ip = 10.15.40.123
mask = 255.255.255.0
gateway = 10.15.40.1
dns = 211.82.96.1
[Match]
ip = 172.17.29.120
mask = 255.255.255.0
gateway = 172.17.29.1
dns = 0.0.0.0
這個配置文件中保存的是不同場合下的IP設置參數。
下面將以生成和讀取這個配置文件為例,進行講解。
Python(v3)讀取方法
首先,Python讀取ini配置需要用到ConfigParser包,所以要先載入它。
import configparser
之後我們需要載入配置文件。
config=configparser.ConfigParser()
#IpConfig.ini可以是一個不存在的文件,意味著准備新建配置文件。
config.read("IpConfig.ini")
接下來,我們可以使用configparser.add_section()向配置文件中添加一個Section。
#添加節School
config.add_section("School")
注意:如果文件中已經存在相應的項目,則不能再增加同名的節。
然後可以使用configparser.set()在節School中增加新的參數。
#添加新的IP地址參數
config.set("School","IP","192.168.1.120")
config.set("School","Mask","255.255.255.0")
config.set("School","Gateway","192.168.1.1")
config.set("School","DNS","211.82.96.1")
你可以以同樣的方式增加其它幾項。
#由於ini文件中可能有同名項,所以做了異常處理
try:
config.add_section("Match")
config.set("Match","IP","172.17.29.120")
config.set("Match","Mask","255.255.255.0")
config.set("Match","Gateway","172.17.29.1")
config.set("Match","DNS","0.0.0.0")
except configparser.DuplicateSectionError:
print("Section 'Match' already exists")
增加完所有需要的項目後,要記得使用configparser.write()進行寫入操作。
config.write(open("IpConfig.ini", "w"))
以上就是寫入配置文件的過程。
接下來我們使用configparser.get()讀取剛才寫入配置文件中的參數。讀取之前要記得讀取ini文件。
ip=config.get("School","IP")
mask=config.get("School","mask")
gateway=config.get("School","Gateway")
dns=config.get("School","DNS")
print((ip,mask+"\n"+gateway,dns))
完整示例
下面是一個完整的示常式序,他將生成一個IpConfig.ini的配置文件,再讀取文件中的數據,輸出到屏幕上。
# -*- coding: utf-8 -*-
import configparser
#讀取配置文件
config=configparser.ConfigParser()
config.read("IpConfig.ini")
#寫入宿舍配置文件
try:
config.add_section("School")
config.set("School","IP","10.15.40.123")
config.set("School","Mask","255.255.255.0")
config.set("School","Gateway","10.15.40.1")
config.set("School","DNS","211.82.96.1")
except configparser.DuplicateSectionError:
print("Section 'School' already exists")
#寫入比賽配置文件
try:
config.add_section("Match")
config.set("Match","IP","172.17.29.120")
config.set("Match","Mask","255.255.255.0")
config.set("Match","Gateway","172.17.29.1")
config.set("Match","DNS","0.0.0.0")
except configparser.DuplicateSectionError:
print("Section 'Match' already exists")
#寫入配置文件
config.write(open("IpConfig.ini", "w"))
ip=config.get("School","IP")
mask=config.get("School","mask")
gateway=config.get("School","Gateway")
dns=config.get("School","DNS")
print((ip,mask+"\n"+gateway,dns))
總結
Python讀取ini文件還是十分簡單的,這里我給出的只是一些簡單的使用方法,如果想用更高級的功能,比如和注釋有關的功能。可以參考Pyhton官方文檔
Ⅱ 怎麼更改pylint的默認配置文件
獲取幫助信息
pylint安裝成功後,可以通過運行"pylint --help"來快速查看pylint的幫助信息;相關信息基本能夠支撐起快速使用起來pylint的基本功能。
bob@Ubuntu:~$ pylint --help
No config file found, using default configuration
Usage: pylint [options] mole_or_package
Check that a mole satisfies a coding standard (and more !).
pylint --help
Display this help message and exit.
pylint --help-msg <msg-id>[,<msg-id>]
Display help messages about given message identifiers and exit.
Options:
--version show program's version number and exit
-h, --help show this help message and exit
--long-help more verbose help.
Master:
--rcfile=<file> Specify a configuration file.
-E, --errors-only In error mode, checkers without error messages are
disabled and for others, only the ERROR messages are
displayed, and no reports are done by default
--ignore=<file>[,<file>...]
Add files or directories to the blacklist. They should
be base names, not paths. [current: CVS]
Commands:
--help-msg=<msg-id>
Display a help message for the given message id and
exit. The value may be a comma separated list of
message ids.
--generate-rcfile Generate a sample configuration file according to the
current configuration. You can put other options
before this one to get them in the generated
configuration.
Messages control:
-e <msg ids>, --enable=<msg ids>
Enable the message, report, category or checker with
the given id(s). You can either give multiple
identifier separated by comma (,) or put this option
multiple time. See also the "--disable" option for
examples.
-d <msg ids>, --disable=<msg ids>
Disable the message, report, category or checker with
the given id(s). You can either give multiple
identifiers separated by comma (,) or put this option
multiple times (only on the command line, not in the
configuration file where it should appear only
once).You can also use "--disable=all" to disable
everything first and then reenable specific checks.
For example, if you want to run only the similarities
checker, you can use "--disable=all
--enable=similarities". If you want to run only the
classes checker, but have no Warning level messages
displayed, use"--disable=all --enable=classes
--disable=W"
Reports:
-f <format>, --output-format=<format>
Set the output format. Available formats are text,
parseable, colorized, msvs (visual studio) and html.
You can also give a reporter class, eg
mypackage.mymole.MyReporterClass. [current: text]
-r <y_or_n>, --reports=<y_or_n>
Tells whether to display a full report or only the
messages [current: yes]
--msg-template=<template>
Template used to display messages. This is a python
new-style format string used to format the message
information. See doc for all details
生成配置文件
可以通過"pylint --generate-rcfile"生成配置文件模板,可以在模板文件上定製相關的統一的配置文件。配置文件中包含了master, message control, reports, typecheck, similarities, basic, variables, format, design, classes, imports, exception相關的lint配置信息,用戶可以進行私人訂制。
bob@Ubuntu:~$ cat pylint.conf
[MASTER]
# Specify a configuration file.
#rcfile=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Profiled execution.
profile=no
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=CVS
# Pickle collected data for later comparisons.
persistent=yes
# List of plugins (as comma separated values of python moles names) to load,
# usually to register additional checkers.
load-plugins=
[MESSAGES CONTROL]
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time. See also the "--disable" option for examples.
#enable=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once).You can also use "--disable=all" to
# disable everything first and then reenable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
#disable=
disable=logging-not-lazy, line-too-long, trailing-whitespace, bare-except, broad-except
[REPORTS]
# Set the output format. Available formats are text, parseable, colorized, msvs
# (visual studio) and html. You can also give a reporter class, eg
# mypackage.mymole.MyReporterClass.
output-format=text
# Put messages in a separate file for each mole / package specified on the
# command line instead of printing them on stdout. Reports (if any) will be
# written in a file name "pylint_global.[txt|html]".
files-output=no
# Tells whether to display a full report or only the messages
reports=yes
# Python expression which should return a note less than 10 (10 is the highest
# note). You have access to the variables errors warning, statement which
# respectively contain the number of errors / warnings messages and the total
# number of statements analyzed. This is used by the global evaluation report
# (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
Ⅲ python3 如何創建一個.ini的配置文件。
1、說明:
python3使用configparser模塊來處理ini配置文件。
2、代碼示例:
需要生成conf.ini配置文件如下:
[config]
v1 = 100
v2 = abc
v3 = true
v4 = 123.45
python代碼:
import configparser
# 載入現有配置文件
conf = configparser.ConfigParser()
# 寫入配置文件
conf.add_section('config') #添加section
# 添加值
conf.set('config', 'v1', '100')
conf.set('config', 'v2', 'abc')
conf.set('config', 'v3', 'true')
conf.set('config', 'v4', '123.45')
# 寫入文件
with open('conf.ini', 'w') as fw:
conf.write(fw)
# 讀取配置信息
v1 = conf.getint('config', 'v1')
v2 = conf.get('config', 'v2')
v3 = conf.getboolean('config', 'v3')
v4 = conf.getfloat('config', 'v4')
print('v1:', v1)
print('v2:', v2)
print('v3:', v3)
print('v4:', v4)
打開conf.ini文件檢查內容
3、模塊常用函數:
1)讀取配置文件
read(filename) 直接讀取ini文件內容
sections() 得到所有的section,並以列表的形式返回
options(section) 得到該section的所有option
items(section) 得到該section的所有鍵值對
get(section,option) 得到section中option的值,返回為string類型
getint(section,option) 得到section中option的值,返回為int類型,還有相應的getboolean()和getfloat() 函數。
2)寫入配置文件
add_section(section) 添加一個新的section
set( section, option, value) 對section中的option進行設置,需要調用write將內容寫入配置文件。
Ⅳ 怎麼在python中創建配置文件
讀取config中info段中的name變數值.最後講講如何設置值.使用set(段名,變數名,值)
來設置變數.config.set(''info'',''age'',''21'')
表示把info段中age變數設置為21.
就這么簡單.