Jor*_*sen 100 python ini python-3.x
我需要使用Python3 读取,编写和创建一个INI文件.
FILE.INI
default_path = "/path/name/"
default_file = "file.txt"
Run Code Online (Sandbox Code Playgroud)
Python文件:
# Read file and and create if it not exists
config = iniFile( 'FILE.INI' )
# Get "default_path"
config.default_path
# Print (string)/path/name
print config.default_path
# Create or Update
config.append( 'default_path', 'var/shared/' )
config.append( 'default_message', 'Hey! help me!!' )
Run Code Online (Sandbox Code Playgroud)
更新的 FILE.INI
default_path = "var/shared/"
default_file = "file.txt"
default_message = "Hey! help me!!"
Run Code Online (Sandbox Code Playgroud)
Rik*_*ggi 126
这可以从一开始:
import configparser
config = configparser.ConfigParser()
config.read('FILE.INI')
print(config['DEFAULT']['path']) # -> "/path/name/"
config['DEFAULT']['path'] = '/var/shared/' # update
config['DEFAULT']['default_message'] = 'Hey! help me!!' # create
with open('FILE.INI', 'w') as configfile: # save
config.write(configfile)
Run Code Online (Sandbox Code Playgroud)
您可以在官方的configparser文档中找到更多信息.
Ago*_*ino 68
这是一个完整的读取,更新和写入示例.
输入文件test.ini
[section_a]
string_val = hello
bool_val = false
int_val = 11
pi_val = 3.14
Run Code Online (Sandbox Code Playgroud)
工作代码.
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser # ver. < 3.0
# instantiate
config = ConfigParser()
# parse existing file
config.read('test.ini')
# read values from a section
string_val = config.get('section_a', 'string_val')
bool_val = config.getboolean('section_a', 'bool_val')
int_val = config.getint('section_a', 'int_val')
float_val = config.getfloat('section_a', 'pi_val')
# update existing value
config.set('section_a', 'string_val', 'world')
# add a new section and some values
config.add_section('section_b')
config.set('section_b', 'meal_val', 'spam')
config.set('section_b', 'not_found_val', '404')
# save to a file
with open('test_update.ini', 'w') as configfile:
config.write(configfile)
Run Code Online (Sandbox Code Playgroud)
输出文件test_update.ini
[section_a]
string_val = world
bool_val = false
int_val = 11
pi_val = 3.14
[section_b]
meal_val = spam
not_found_val = 404
Run Code Online (Sandbox Code Playgroud)
原始输入文件保持不变.
我的backup_settings.ini文件中的内容
[Settings]
year = 2020
Run Code Online (Sandbox Code Playgroud)
用于阅读的python代码
import configparser
config = configparser.ConfigParser()
config.read('backup_settings.ini') #path of your .ini file
year = config.get("Settings","year")
print(year)
Run Code Online (Sandbox Code Playgroud)
用于写作或更新
from pathlib import Path
import configparser
myfile = Path('backup_settings.ini') #Path of your .ini file
config.read(myfile)
config.set('Settings', 'year','2050') #Updating existing entry
config.set('Settings', 'day','sunday') #Writing new entry
config.write(myfile.open("w"))
Run Code Online (Sandbox Code Playgroud)
输出
[Settings]
year = 2050
day = sunday
Run Code Online (Sandbox Code Playgroud)
该标准ConfigParser通常需要通过 访问config['section_name']['key'],这并不有趣。稍加修改即可提供属性访问:
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
Run Code Online (Sandbox Code Playgroud)
AttrDict是一个派生自dict它的类,允许通过字典键和属性访问进行访问:这意味着a.x is a['x']
我们可以在ConfigParser:
config = configparser.ConfigParser(dict_type=AttrDict)
config.read('application.ini')
Run Code Online (Sandbox Code Playgroud)
现在我们得到application.ini:
[general]
key = value
Run Code Online (Sandbox Code Playgroud)
作为
>>> config._sections.general.key
'value'
Run Code Online (Sandbox Code Playgroud)
ConfigObj是 ConfigParser 的一个很好的替代品,它提供了更多的灵活性:
它有一些缺点:
=……(拉取请求)fuabr =而不是fubar看起来很奇怪和错误。| 归档时间: |
|
| 查看次数: |
147823 次 |
| 最近记录: |