2014-02-20 74 views
1

在一個文件中,我的查詢塊以空行分隔(可以是一個或多個空行)。有沒有更好的方法將查詢放入列表中?從文件中檢索文本塊

防爆文件:

select * from tbA 
where colA= '2' 

select * from tbB 
where colB = 'c' 
order by colc 



select * from tbC 

代碼我到目前爲止已經:

queries = list() 
with open(sql_file_path, 'rb') as f: 
    lines = f.readlines() 
    i = 0 
    while i < len(lines): 
     query = '' 
     while i < len(lines) and not lines[i].isspace(): 
      query += lines[i] 
      i += 1 
     while i < len(lines) and lines[i].isspace(): 
      i += 1 
     queries.append(query.strip()) 

我要找的結果是一個包含完整的查詢的查詢的不只是一條線的列表。

回答

1
with open(path) as f: 
    lines = [line.strip() for line in f if line] 

如果行不是空白,list comp會逐行遍歷文件並將其構建到列表中。如果它是空白的,它將忽略它。

根據您的編輯文本,只需在空行上分割即可(\n\n)。

with open(path) as f: 
    lines = [query for query in f.read().split("\n\n") if query] 

您還可以通過正則表達式做到這一點:

import re 

with open(path) as f: 
    queries = re.split(r"\n\n+",f.read()) 
+0

我不想非空行的列表,我想完成的查詢列表。我用更好的例子更新了這個問題。 – ziddarth

+0

@ziddarth編輯。這是更醜陋的,但應該做的伎倆。 –

+0

+1如果行是空白的,但不是空的,可以使用're'(regex)模塊提供的'split()' – slezica

0
queries = [query.strip() for query in re.split(r"(\r\n)(\r\n)+", all_text,) if query.strip()]