2015-12-02 57 views
0

我正在使用默认字典和分隔符来读取文本文件中的内容。避免在默认字典中填充空行或空格

考虑到文本文件有以下内容。

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

你可以添加一个检查,以确保该行拥有实际的非空白字符:

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

零长度字符串评估为False在布尔上下文,以及所有其他字符串评估为True,所以这应该足以检测空行。