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

该回答引用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)

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