Python configparser if语句并编辑.ini文件中的数据

2024-10-03 11:12:31 发布

您现在位置:Python中文网/ 问答频道 /正文

如果数据等于示例,如何使用if语句编辑数据

if DisplayMenu == "1":
        config = ConfigParser()
        if config["SETTINGS"] == {"Tutorial": "True"}:
            config["SETTINGS"] = {
                "Tutorial": "False"
                }
        if config["SETTINGS"] == {"Tutorial": "False"}:
            config["SETTINGS"] = {
                "Tutorial": "True"
                }

我想做的是,当“设置”选项卡中的“值”tutorial等于true时,然后更改为false,反之亦然。如何做到这一点?我用这个时出错了

Traceback (most recent call last):
  File "C:\Users\Stagiair\Desktop\Immortal Conquest\Main\Settings.py", line 80, in <module>
    DisplayMenu()
  File "C:\Users\Stagiair\Desktop\Immortal Conquest\Main\Settings.py", line 27, in DisplayMenu
    print("[1] Tutorial  = " + config['SETTINGS']['Tutorial'])
  File "C:\Users\Stagiair\AppData\Local\Programs\Python\Python39\lib\configparser.py", line 960, in __getitem__
    raise KeyError(key)
KeyError: 'SETTINGS'

我用来创建.ini文件的代码

#Makes a Settingsfile
def CreateSettingsFile():
    try:
        import os, sys, time, pickle, colorama, threading, ctypes
        from configparser import ConfigParser
    except Exception as e:
        print("Some modules are mssing! Install them and try again! {}".format(e))
    os.system("cls")
    #Get the configparser object
    config = ConfigParser()

    #Assume we need 2 sections in the config file, let's call them SETTINGS and USERINFO
    config["SETTINGS"] = {
        "Music": "True",
        "Tutorial": "True",
        "GameSaves": "True"
    }
    config["USERINFO"] = {
        "username": "Not Set"
    }
    config["GAMEITEMS"] = {
        "EXP": "None",
        "Items" : "None",
        "Kills" : "None",
        "Saved" : "None"
    }
    #Write the above sections to config.ini file
    with open('GameSaves/config.ini', 'w') as conf:
        config.write(conf)
    os.system("cls")

Tags: inpynoneconfigtrueifsettingsline