You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Configparser写入ini文件成功但读取返回空列表问题排查

问题现象

生成的ini文件内容
用于创建、读取ini配置的类运行异常:ini文件中已经写入了全部配置段,但程序执行读取操作时始终返回空列表[]。该功能的基础版本此前在Anaconda Navigator环境中可正常运行。
从截图可见生成的ini文件非空,写入操作已执行,但无论是写入函数内直接打印读取结果,还是其他函数调用读取该文件,均返回空列表[]。
问题原代码如下:

class cSetup():
import os
import time
import datetime
import configparser as configparser
"""Class creates an ini file, this ini file contains a number of settings which can be read by the get function.
the program will later access this file to check for certain settings.
If the file is not existing yet, a function within the class will create it
"""
config = configparser.ConfigParser()

def write_setup(self):
    if os.path.exists("Setup.ini"):
        setup_file = open("Setup.ini", "r")
        print(self.config.read(setup_file))
        setup_file.close()
    else:
        """This function is the initial setup, it writes all the necessary information to a .ini file."""
        global config
        """Asks user for a name"""
        Name = input("Please enter your name, note this can be changed in the settings""\n"
                               "Please enter the name here: ")
        self.time.sleep(1)

        """asks user for prefered input method"""
        PreferredInput = input("Input method required: 0 Shutdown, 1 Voice Commands, 2 Text Commands, 3 Dev Mode: ")

        setup_file = open("Setup.ini", "w")
        setup_file
        self.config.write(setup_file)
        self.config.add_section("Setup state")
        self.config.set("Setup state", "Activated?", "True")  # Convert to Bool later
        section_option = "Settings"
        self.config.add_section(section_option)
        self.config.set(section_option, "Name", Name)
        self.config.set(section_option, "Preferred Input", PreferredInput)  # Convert to int later
        self.config.write(setup_file)
        setup_file = open("Setup.ini", "r")
        print(self.config.read(setup_file))
        setup_file.close()
故障原因
  • 写入逻辑顺序错误:第一次调用self.config.write(setup_file)时,config对象内还未添加任何section和配置项,相当于向刚打开的空文件写入了空白内容,属于无效操作。
  • 文件句柄未正常关闭:添加完所有配置执行第二次写入后,没有关闭以写入模式打开的setup_file句柄,操作系统IO缓存未刷新到磁盘,此时直接打开新句柄读取文件,大概率只能读到空内容。
  • 代码存在多处不规范写法:导入语句写在类内部、无意义的global config声明、单独一行无任何作用的setup_file语句、config对象定义为类属性易出现多实例污染问题。
修复方案
  1. 调整写入顺序:先向config对象添加完所有section和配置项,再执行文件写入操作,删除提前写入空内容的无效代码。
  2. 改用with上下文管理器操作文件,自动处理文件关闭和缓存刷新,避免手动调用close()的遗漏问题。
  3. 修正代码规范问题:将导入语句移到文件顶部,config对象改为实例属性,删除无意义的全局变量声明和空代码行。
  4. 读取文件时直接传入文件路径给config.read()方法,无需手动打开文件句柄,同时指定文件编码避免乱码。

修复后可正常运行的代码:

import os
import time
import configparser

class cSetup():
    """Class creates an ini file, this ini file contains a number of settings which can be read by the get function.
    the program will later access this file to check for certain settings.
    If the file is not existing yet, a function within the class will create it
    """
    def __init__(self):
        self.config = configparser.ConfigParser()

    def write_setup(self):
        if os.path.exists("Setup.ini"):
            read_result = self.config.read("Setup.ini", encoding="utf-8")
            print(read_result)
        else:
            Name = input("Please enter your name, note this can be changed in the settings\n"
                               "Please enter the name here: ")
            time.sleep(1)

            PreferredInput = input("Input method required: 0 Shutdown, 1 Voice Commands, 2 Text Commands, 3 Dev Mode: ")

            # 先完成所有配置项的添加
            self.config.add_section("Setup state")
            self.config.set("Setup state", "Activated?", "True")
            section_option = "Settings"
            self.config.add_section(section_option)
            self.config.set(section_option, "Name", Name)
            self.config.set(section_option, "Preferred Input", PreferredInput)
            
            # 配置添加完成后一次性写入文件,with自动处理关闭落盘
            with open("Setup.ini", "w", encoding="utf-8") as setup_file:
                self.config.write(setup_file)
            
            # 写入完成后再读取验证
            read_result = self.config.read("Setup.ini", encoding="utf-8")
            print(read_result)

内容的提问来源于stack exchange,提问作者JustWannaCodeInPeace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 23:48:39