孙永亮556 2023-03-21 23:58 采纳率: 100%
浏览 19
已结题

python configoarser模块使用问题

建立了一个test.ini文件,内容是这样的:

[book]
title = 444

引入模块,我的思路是这样的,查询test.ini中给所有的sections,如果book2在列表中,打印Y。否则在test.ini中写入book2,并且在book2.ini中写入title信息,但是结果不太对。

import configparser

config = configparser.ConfigParser()
config.read('test.ini')

if 'book2' in config.sections():
    print('Y')   
else:
    config['book2'] = {'title': 555}
    config.write(open('test.ini', 'w'))
    
    config['title'] = {'autor': 666}
    config.write(open('book2.ini', 'w'))

结果是这样的,test.ini中所有的信息也写入到了book2.ini中,这是为什么呢?难道是因为我开头读取了test.ini的信息?我试了在后面新建文件,用config.read()打开,再写入,结果还是一样的。下面是输出test.ini和book2.ini的结果:

# test.ini
[book1]
title = 444

[book2]
title = 555
#book2.ini
[book1]
title = 444

[book2]
title = 555

[title]
autor = 666
  • 写回答

1条回答 默认 最新

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2023-03-22 00:27
    关注

    该回答引用ChatGPT

    您的代码中存在一些问题,导致输出的结果不符合您的预期。以下是您需要修正的问题和改进的建议:

    • 首先,您在创建 book2 时将其添加到了 test.ini 中,但是后续却将 title 添加到了 test.ini 而不是 book2.ini 中。因此,您需要更改以下代码:
      config['title'] = {'autor': 666}
      config.write(open('book2.ini', 'w'))
      
      应该修改为:
      config2 = configparser.ConfigParser()
      config2['book2'] = {'title': 555, 'autor': 666}
      with open('book2.ini', 'w') as f:
        config2.write(f)
      

    这里创建了一个新的 ConfigParser 对象 config2,并将 title 和 autor 添加到了 book2 中,最后将其写入 book2.ini。

    • 其次,在写入 test.ini 或者 book2.ini 时,您需要将之前读取的内容清空,以避免将其写入到文件中。因此,在写入文件之前添加以下代码:
      config.clear()
      
      这将清空 config 对象中存储的所有内容,以便您可以将新的数据写入到文件中。
    • 最后,您需要检查 test.ini 和 book2.ini 文件是否存在,如果不存在,则需要创建它们。因此,您可以添加以下代码:
      import os
      if not os.path.exists('test.ini'):
        with open('test.ini', 'w') as f:
            pass
      if not os.path.exists('book2.ini'):
        with open('book2.ini', 'w') as f:
            pass
      
      这将检查文件是否存在,如果不存在,则创建一个空文件。

    综上所述,以下是您可以尝试的修正代码:

    import os
    import configparser
    
    if not os.path.exists('test.ini'):
        with open('test.ini', 'w') as f:
            pass
    
    if not os.path.exists('book2.ini'):
        with open('book2.ini', 'w') as f:
            pass
    
    config = configparser.ConfigParser()
    config.read('test.ini')
    
    if 'book2' in config.sections():
        print('Y')
    else:
        config['book2'] = {'title': 555}
        with open('test.ini', 'w') as f:
            config.write(f)
    
        config2 = configparser.ConfigParser()
        config2['book2'] = {'title': 555, 'autor': 666}
        with open('book2.ini', 'w') as f:
            config2.write(f)
    

    希望这可以帮助您解决问题!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 3月30日
  • 已采纳回答 3月22日
  • 创建了问题 3月21日

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来