2014-06-27 47 views
1

我有一個測試文件包含表單的多個序列(不Python腳本)追溯一個文件對象的當前位置:Python的 - 有沒有辦法通過一個線

TESTFILE (不Python腳本)

#Gibberish 
#Gibberish 
newSeq name-and-details 
10 something 
20 something 
30 something 
newSeq name-and-details 
10 something 
20 something 
30 something 
#Gibberish 
#Gibberish 
newSeq name-and-details 
...and so forth 

然後,我有一個python腳本讀取這個文件作爲輸入。對於每個新序列,都會創建一個新的python-list來存儲內容。

inputFile = open('testFile','r') 
moreSeq = True 
newLine = inputFile.readline() 
while moreSeq: 
    while (not ('newSeq' in newLine)): 
    newLine = inputFile.readline() 
    newList = [] 
    moreSeq = newList.listEntry(inputFile) 
    listDB.append(newList) 

但是當文件對象INPUTFILE傳遞給一個ListEntry方法,我希望它的位置將指向newSeq的開端,而不是隨後的指數:

即我想這點到newSeq#1 line,而不是10東西

如何追溯文件對象的位置由一行或按行固定的度量值。我相信尋求在這種情況下不起作用。

回答

2

這是通常由unreading行如下面的代碼來解決的一個常見問題:

class SmartReader(object): 
    def __init__(self, file): 
     self.file = file 
     self.lastline = None 
    def readline(self): 
     if self.lastline is not None: 
      ln = self.lastline 
      self.lastline = None 
      return ln 
     return self.file.readline() 
    def unreadline(self, line): 
     self.lastline = line   


    ... 


    fd = SmartReader(open("file.txt")) 
    readMore = True 
    while readMore: 
     line = fd.readline() 
     if its_newSeq(): 
      fd.unreadline(line) 
      close_the_previous_sequence() 
     else: 
      process_the_line() 
1

您可以使用file.tell()查看文件中的當前位置(以字節爲單位),並使用file.seek()將光標置於任意新位置。有了這2種方法和線的長度,你剛纔讀它應該是很容易做你打算什麼

f = open('foo.txt') 
f.readline() # output `bar` 
f.tell() # output 3 
f.seek(0) # go to the start of the file 
1

我覺得同樣可以實現如下:

lists = [] 
with open('testFile','r') as f: 
    for line in f: 
     if '#Gib' in line: 
      pass 
     elif 'newSeq' in line: 
      lists.append([]) 
     else: 
      lists[-1].append(line) 

這將返回具有必需行的列表清單。你可以使用任何你想要的數據結構。如果newSeq名稱和細節是獨特的,那麼我寧願哈希列表將是一個更好的數據結構。

0

的直接解決問題的方法可以是使用itertools.chain,通過執行

moreSeq = newList.listEntry(itertools.chain([newline], inputFile)) 

這樣,listEntry方法就會看到與您所描述的一致的迭代。但是,我懷疑這並不能解決listEntry分析線路和返回時的問題 - 您可能希望在發生這種情況時重新倒帶文件,因爲listEntry也可能會消耗#Gibberish線路中的一條。

我必須說你的代碼看起來更像C而不是Python。我認爲線條閱讀循環會更清晰,作爲for line in f樣式循環。重新思考你的方法來更好地與語言保持一致可能是一個更好的主意。

+0

但是使用「for f in line」並不能解決問題。我可以將newLine傳遞給函數listEntry並完成它,但似乎無法追溯任何固定數量的位置。 – HindK

相關問題