如何使用Python3读取和写入INI文件?

202 投票
10 回答
369012 浏览
提问于 2025-04-17 10:22

我需要用Python3来读取、写入和创建一个INI文件。

FILE.INI

default_path = "/path/name/"
default_file = "file.txt"

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!!' )

更新后的 FILE.INI

default_path    = "var/shared/"
default_file    = "file.txt"
default_message = "Hey! help me!!"

10 个回答

14

http://docs.python.org/library/configparser.html

在这种情况下,Python的标准库可能会很有帮助。

126

这里有一个完整的读取、更新和写入的例子。

输入文件是 test.ini

[section_a]
string_val = hello
bool_val = false
int_val = 11
pi_val = 3.14

这是可以正常工作的代码。

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)

输出文件是 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

原来的输入文件没有被修改。

257

这可以作为一个开始:

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)

你可以在官方的configparser文档中找到更多信息。

撰写回答