2012-07-12 31 views
0

我想輸出makeList [start]的索引到makeList [end]。我有所有正確的開始和結束值,總共約11對。但是,我沒有得到正確的輸出,因爲它沒有打印出所有可能的輸出。爲什麼會發生?我輸出文件中的數據沒有打印出應該有的所有結果

def searchPFAM(fname): 
    with open(fname,'rb') as f: 
     root = etree.parse(f) 
     for lcn in root.xpath("/protein/match[@dbname='PFAM']/lcn"): 
      try: 
      start = int(lcn.get("start")) 
      end = int(lcn.get("end")) 
      yield start, end 
      except (TypeError , ValueError) as e: 
      pass 

uniprotID ='Q14591' 

def createRef(): 
    fileInput = open(uniprotID +'.txt','r') 
    readAA = fileInput.read() 
    store_value = (readAA.partition('\n')) 
    aaSequence = store_value[2].replace('\n', '') 
    makeList = list(aaSequence) 
    return makeList 

makeList = createRef() 

for start, end in searchPFAM(fname): 
    print start, end 
    if start <= end: 
     with open('newfile.txt','w') as fileinput: 
      while start <= end: 
       result = makeList[start] 
       fileinput.write(result) 
       start += 1 

回答

3

只是一個猜測,但你可能想:

with open('newfile.txt','w') as fileinput: 
    for start, end in searchPFAM(fname): 
     print start, end 
     if start <= end: 
      while start <= end: 
       result = makeList[start] 
       fileinput.write(result) 
       start += 1 

你的舊版本只寫1點開始/結束循環到該文件,關閉它,然後打開一個新文件(與舊文件名相同),寫入1個開始/結束循環,關閉文件...換句話說,你正在用每次循環迭代重寫文件。

+0

這個作品謝謝 – 2012-07-12 19:58:49

+2

沒問題。樂意效勞。有時候,這些簡單的東西坐在那裏盯着你,他們很難看到/跟蹤。祝你好運。 – mgilson 2012-07-12 19:59:46

0

最常見的原因:您需要在腳本終止前刷新輸出文件。從上面

片段:

with open('newfile.txt','w') as fileinput: 
     while start <= end: 
      result = makeList[start] 
      fileinput.write(result) 
      start += 1 
fileinput.flush() 
+3

他正在使用'with',因此當該塊被退出時,文件應該自動關閉(並刷新) – Levon 2012-07-12 19:52:24

+0

@Levon,它確實......'fileinput奇怪地保留在作用域中,但實際上是一個關閉的fileobj,所以任何操作都會失敗 – 2012-07-12 19:55:13

+0

當我將flush()放入時,我收到了錯誤消息:ValueError:關閉文件上的I/O操作 – 2012-07-12 19:57:37

相關問題