简体   繁体   English

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

[英]Python ConfigParser - Create File if it Doesn't Exist

So I am working on creating a program in Python that reads a .ini file to set up some boot variables for the main program. 所以我正在创建一个Python程序,它读取一个.ini文件来为主程序设置一些启动变量。 My only thing is, I want the program on initialization, to check if the .ini file exists, and if it doesn't, create it with a set of default values. 我唯一的想法是,我希望程序在初始化时检查.ini文件是否存在,如果不存在,则使用一组默认值创建它。 Kind of a preemptive bug fix on if someone accidentally deletes the file. 如果有人意外删除了该文件,那就是一种先发制人的错误修复方法。

I can't seem to find any examples anywhere of how to do this, and I'm not super experienced with Python (only been programming with it for about a week) so I'd appreciate any assistance :) 我似乎无法找到任何关于如何做到这一点的例子,而且我对Python没有超级经验(只用它编程大约一周)所以我很感激任何帮助:)

EDIT: Upon further thought, I want to pursue this a bit further. 编辑:经过进一步思考,我想进一步追求这一点。

Let's assume the file does exist. 我们假设文件确实存在。 How do I check it to make sure it has the appropriate sections? 如何检查以确保它具有适当的部分? If it doesn't have the appropriate sections, how would I go about deleting the file or removing the contents and rewriting the contents of the file? 如果它没有相应的部分,我将如何删除文件或删除内容并重写文件的内容?

I'm trying to idiot proof this :P 我试图用这个白痴证明:P

You can use ConfigParser and the OS library, here's a quick example: 您可以使用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()

Output : 输出

[DEFAULT]
test = 45
test2 = yes

Linked above are the docs that are extremely useful to learn more about writing configuration files and other in-built modules. 以上链接的文档对于了解有关编写配置文件和其他内置模块的更多信息非常有用。

Note : I'm kind of new to python, so if anyone knows a better approach let me know I'll edit my answer! 注意 :我是python的新手,所以如果有人知道更好的方法让我知道我会编辑我的答案!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM