[英]Read a comma separated INI file in python?
我有一个 INI 文件
[default]
hosts=030, 031, 032
我有逗号分隔的值。 我可以用一个简单的方法读取所有值
comma_separated_values=config['default']['hosts']
这样我就可以获得变量中的所有值。 但是我怎样才能遍历这个 INI 文件,以便我可以将所有这些值存储为一个列表而不是变量。
假设这些值必须是整数,您可能希望在从逗号分隔的字符串中提取列表后将它们转换为整数。
继科尔文的回答之后:
values_list = [int(str_val) for str_val in config['default']['hosts'].split(',')]
或者,如果每个数字的零前缀应该表示它们是八进制:
values_list = [int(str_val, 8) for str_val in config['default']['hosts'].split(',')]
由于这些是作为字符串读入的,因此您应该能够执行此操作并将其存储在列表中
values_list = config['default']['hosts'].split(',')
您可以将其概括如下:
import ConfigParser
import io
# Load the configuration file
def read_configFile():
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.read("config.ini")
# List all contents
print("List all contents")
for section in config.sections():
#print("Section: %s" % section)
for options in config.options(section):
if (options == 'port'):
a = config.get(section,options).split(',')
for i in range(len(a)):
print("%s:::%s" % (options, a[i]))
else:
print("%s:::%s" % (options, config.get(section, options)))
read_configFile()
config.ini
[mysql]
host=localhost
user=root
passwd=my secret password
db=write-math
port=1,2,3,4,5
[other]
preprocessing_queue = ["preprocessing.scale_and_center",
"preprocessing.dot_reduction",
"preprocessing.connect_lines"]
use_anonymous=yes
您可以读取文件的内容并使用 split(',') 将其拆分。 尝试使用下面的代码。
with open('#INI FILE') as f:
lines = f.read().split(',')
print(lines) # Check your output
print (type(lines)) # Check the type [It will return a list]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.