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

ConfigParser - Create file if it doesn't exist

所以我正在 Python 中创建一个程序,该程序读取 .ini 文件以为主程序设置一些引导变量。我唯一的事情是,我希望程序在初始化时检查 .ini 文件是否存在,如果不存在,则使用一组默认值创建它。如果有人不小心删除了文件,则会先发制人地修复错误。

我似乎无法在任何地方找到如何执行此操作的任何示例,而且我对 Python 也不是很有经验(只用它编程了大约一个星期)所以我很感激任何帮助:)

编辑:经过深思熟虑,我想更进一步。

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

我正在努力证明这一点 :P

您可以使用 ConfigParser and the OS 库,这是一个简单的示例:

#!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

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

注意:我是 python 的新手,所以如果有人知道更好的方法请告诉我,我会编辑我的答案!