2015-12-02 45 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,所以這應該足以檢測空行。