2015-08-28 62 views
1

我有一些文件,其中有這樣一些數據:查找值,關鍵字之間,使用python

begin of file 
1,2,3,4,5,6,7 
end of file 

我想讀取這個文件,所以我曾嘗試:

filename = open('file','r') 
for line in filename: 
    print line 

但現在我需要在txt文件中搜索關鍵字'開始文件'和'結束文件',然後將2個關鍵字之間的值保存到列表中。 我試過這個:

Listsave = [] 
filename = open('file', 'r') 
for line in filename: 
    if "begin of file" in line: 
     listsave.append(line.next()) 

但它似乎沒有工作。

我該如何處理? 非常感謝

+0

修改循環中循環變量(line.next())是不是好的做法。您可以設置一個二進制變量來標記是否記錄行 – jf328

+2

「但它似乎不起作用。」你怎麼知道? – Kevin

回答

1

您可以使用下面的方法,它能夠使用Python的CSV庫到您的行拆分爲適合列。這樣可以更容易地支持不同的分隔符或需要時的額外引用。

import StringIO, csv 

with open('file.txt', 'r') as f_input: 
    begin = False 
    rows = [] 

    for line in f_input: 
     if line.startswith("end of file"): 
      break 
     elif begin: 
      rows.append(next(csv.reader(StringIO.StringIO(line)))) 
     elif line.startswith("begin of file"): 
      begin = True 

    print rows 

所以以下類型輸入:

stuff 
begin of file 
1,2,3,4,5,6,7 
8,9,10 
11,12,13,14,15 
end of file 
more stuff 

這將創建:

[['1', '2', '3', '4', '5', '6', '7'], ['8', '9', '10'], ['11', '12', '13', '14', '15']] 
1
with open("file") as file: 
    data = file.read() 
result = data.partition("begin of file")[2].rpartition("end of file")[0].strip().split(",") 
print result 

結果:

['1', '2', '3', '4', '5', '6', '7'] 
+0

read()方法將整個文件的內容讀入內存。 Rpartition實質上是一個更高級的分割。雖然代碼少了,但我認爲這個解決方案做了很多不必要的處理。 –

+0

如果OP的文件特別大,這當然是一個有效的擔憂。儘管他們給出的例子並沒有太大區別,但是;-) – Kevin

+0

這是真的,只是意味着它作爲一個普遍的參考。 –

0

這裏,試試這個。它標誌着我們是否已經通過了起點,並在我們超越終點時突破了。

listsave = [] 
filename = open('file', 'r') 
found = False 
for line in filename: 
    if not found: 
     if 'begin of file' in line: 
      found = True 
    else: 
     if 'end of file' in line: 
      break 
     listsave.append(line) 

這對我來說有點凌晨,所以可能會有更好的解決方案。

編輯:

稍乾淨的版本。

with open('file', 'r') as file: 
    found = False 
    saved = [] 
    for line in file: 
     if not found: 
      if 'begin of file' in line: 
       found = True 
     elif 'end of file' in line: 
      break 
     else: 
      saved.append(line) 
1
def getstringbetween(source, first, last): 
try: 
    start = source.index(first) + len(first) 
    end = source.index(last, start) 
    return source[start:end] 
except ValueError: 
    return "" 

用法:

print getstringbetween("abcdefg", "ab", "fg") 

返回:

「CDE」

在你的情況,請閱讀所有文本字符串並調用這個函數。如果需要,將結果返回給列表/數組。

0

你可以嘗試這樣的事情:

filename = open('file', 'r') 
Listsave = [] 
subline = "" 
for line in filename: 
    if "begin of file" in line: 
     continue 
    elif "end of file" in line: 
     Listsave.append(subline) 
    else: 
     subline += line 
print Listsave