避免在默认字典中计算空行或空格

时间:2015-12-02 17:23:32

标签: python defaultdict

我正在使用默认的dict和split来读取文本文件中的内容。

考虑文本文件包含以下内容。

cbdf25542c194a069464f69efff4859a 1.7.6.1
cbdf25542c194a069464f69efff4859a 1.6.7.1
cbdf25542c194a069464f69efff4859a 1.3.6.5

现在考虑它之间有空行,所以它返回错误而不是正确解析它。

如何摆脱它。

即使它有空行也必须正常工作。

考虑下面的代码。

def _ip_fetch(current_tenant_id):

        results = defaultdict(list)
        with open(flat_text_file_location, 'r') as f:
                for row in f.readlines():
                        tenant_id, ip = row.split()
                        results[tenant_id].append(ip)
        ips = results.get(current_tenant_id, None)
        return ips

1 个答案:

答案 0 :(得分:1)

您可以添加一项检查以确保该行包含实际的非空白字符:

            for row in f.readlines():
                if row.strip():
                    tenant_id, ip = row.split()
                    results[tenant_id].append(ip)

零长度字符串在布尔上下文中求值为False,所有其他字符串求值为True,因此这应该足以检测空行。