2

尝试读取文件并从行中创建字典,skippipng 行以 # 符号开头

文件示例:

param1=val1
# here is comment

我的功能:

def readFromFile(name):
    config = {}
    with open(name, "r") as f:         
        for line in f.readlines():
            li=line.lstrip()
            if not li.startswith("#"):
                config[line.split('=')[0]] = line.split('=')[1].strip()
    return config

我得到列表索引超出范围错误

但!如果我尝试跳过以符号“h”开头的行 - 函数运行良好......

4

3 回答 3

6

尝试:

def readFromFile(name):
    config = {}
    with open(name, "r") as f:         
        for line in f.readlines():
            li = line.lstrip()
            if not li.startswith("#") and '=' in li:
                key, value = line.split('=', 1)
                config[key] = value.strip()
    return config

您可能有一个空白行会破坏您的 split()

于 2013-07-31T12:02:06.447 回答
4

您的代码工作得很好,除了既不以 a 开头#也不包含=字符的行。通常,这些是空行。

=拆分前测试字符:

def readFromFile(name):
    config = {}
    with open(name, "r") as f:         
        for line in f.readlines():
            li=line.lstrip()
            if not li.startswith("#") and '=' in li:
                config[line.split('=')[0]] = line.split('=')[1].strip()
    return config

您可以简化代码并使其成为字典理解:

def readFromFile(name):
    with open(name, "r") as f:         
        return {k: v 
            for line in f 
            for (k, v) in (line.strip().split('=', 1),)
            if '=' in line.strip() and line[:1] != '#'}

您可以直接循环f(文件对象);无需先使用将所有行读入内存。我以前只在等号上拆分一次f.readlines().split('=', 1)

于 2013-07-31T12:01:51.770 回答
1

您可以直接返回字典:

 def readFromFile(name):
     with open(name) as f:
         return { line.split('=')[0]:line.split('=')[1].strip() for line in f \
                  if not line.startswith('#' and '=' in line } 
于 2013-07-31T12:06:44.917 回答