简体   繁体   English

Python-ConfigParser-.ini文件太大?

[英]Python - ConfigParser - .ini file too large?

This is my first question on stackoverflow and I have only been involved with python for a short time, but I have a problem with reading an .ini file and I cannot find the answer anywhere. 这是我关于stackoverflow的第一个问题,我只参与了很短一段时间的python,但是我在读取.ini文件时遇到问题,无法在任何地方找到答案。

This is a small piece of my current code: 这是我当前代码的一小部分:

import configparser 
config = configparser.ConfigParser()
config.sections()
config.read("filename.ini")
print(config.sections)

The script runs, but it does not print the names of the sections in my .ini file. 该脚本会运行,但是不会在我的.ini文件中打印各节的名称。 I have waited for more than 15 min, but I still receive nothing. 我已经等待了15分钟以上,但仍然什么也没收到。 Could it be that the file is too large? 可能是文件太大了吗? It is 32.628 KB and I have to do the same thing multiple times so I was hoping I could automate it. 它是32.628 KB,我必须多次执行相同的操作,因此我希望可以实现自动化。

I hope someone can help me out 我希望有人可以帮助我

I'll assume you want to parse a normal INI file, this should be the source code for it (which your file probably does not follow, so you might consider following this format): 我假设您想解析一个普通的INI文件,这应该是它的源代码(您的文件可能不遵循该源代码,因此您可以考虑采用这种格式):

[section_1]
section_1_1: test0
section_1_2: test1
section_1_3: test3

[section_2]
section_2_1: test0
section_2_2: test1
section_2_3: test3

Your code should work - with a small adjustment 您的代码应该可以工作-稍作调整

from configparser import ConfigParser 
config = ConfigParser()
config.sections()
config.read("conf.ini")
print(config.sections())
for section in config.sections():
    for option in config.options(section):
        print("Option: {} in section: {}".format(option, section))

If you have a complex INI file (with sub sections) - then ConfigParser won't be able to help you here, and you'll need another parser for that, check this: ConfigParser getting value from INI file with section and subsection as shown below 如果您有一个复杂的INI文件(包含子节),则ConfigParser将无法在这里为您提供帮助,为此您将需要另一个解析器,请检查此内容: ConfigParser从INI文件中获取带有节和子节的值,如图所示下面

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

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