ConfigParser - 如果文件不存在则创建文件

问题描述 投票:0回答:1

所以我正在用Python创建一个程序,它读取.ini文件为主程序设置一些启动变量。我唯一的事情是,我希望程序在初始化时检查

.ini
文件是否存在,如果不存在,则使用一组默认值创建它。如果有人意外删除该文件,则可以进行先发制人的错误修复。

我似乎在任何地方都找不到如何做到这一点的任何示例,而且我对 Python 的经验也不是很丰富(只用它编程了大约一周),所以我将不胜感激任何帮助:)

编辑:经过进一步思考,我想进一步探讨这一点。

假设该文件确实存在。我如何检查它以确保它具有适当的部分?如果它没有适当的部分,我将如何删除文件或删除内容并重写文件的内容?

我正在尝试白痴证明这一点:P

python config configparser
1个回答
13
投票

您可以使用 ConfigParserOS 库,这是一个简单的示例:

#!usr/bin/python
import configparser, os

config = configparser.ConfigParser()

# Just a small function to write the file
def write_file():
    config.write(open('config.ini', 'w'))

if not os.path.exists('config.ini'):
    config['testing'] = {'test': '45', 'test2': 'yes'}

    write_file()
else:
    # Read File
    config.read('config.ini')

    # Get the list of sections
    print config.sections()

    # Print value at test2
    print config.get('testing', 'test2')

    # Check if file has section
    try:
        config.get('testing', 'test3')

    # If it doesn't i.e. An exception was raised
    except configparser.NoOptionError:
        print "NO OPTION CALLED TEST 3"

        # Delete this section, you can also use config.remove_option
        # config.remove_section('testing')
        config.remove_option('testing', 'test2')

        write_file()

输出

[DEFAULT]
test = 45
test2 = yes

上面链接的文档对于了解有关编写配置文件和其他内置模块的更多信息非常有用。

© www.soinside.com 2019 - 2024. All rights reserved.