2017-05-10 58 views
-1

我試圖找到outfile(of)以字母ATOM開頭的行,然後用它做些事情,但不幸的是它不會遍歷文件。有人知道爲什麼嗎?不重複遍歷文件?

with open(args.infile, "r") as f, open(args.outfile, "w+") as of, open(args.reference,"r") as rf: 
    for line in f: 
     of.write(line) 
    for line in rf: 
     if line[0:3]== "TER": 
      resnum = line[22:27] 
      #resnum_1[resnum] = "TER" 
    for line in of: 
     if line [0:4]== "ATOM": 
      res = line[22:27] 
      if res == resnum: 
       print res 
+0

你把所有的文件在同一時間打開。你有沒有嘗試在不同於你寫信給它的塊中打開'''? – roganjosh

+2

爲什麼你有'''?看起來你可以直接使用'f'。 – user2357112

+0

1)你正在迭代射頻的全部內容,但只抓取以'TER'開頭的最後一行,你想在這裏打破一個更復雜的邏輯嗎? 2)''''等於'f',所以你可以直接使用'f'(並將'f'的內容複製到其他地方的''of') – dantiston

回答

2

丹尼爾的回答給了你正確的理由,但錯誤的建議。

要刷新數據到磁盤,然後將鼠標指針移動到文件的開頭:

# If you're using Python2, this needs to be your first line: 
from __future__ import print_function 

with open('test.txt', 'w') as f: 
    for num in range(1000): 
     print(num, file=f) 
    f.flush() 
    f.seek(0) 
    for line in f: 
     print(line) 

for line in of前只需添加of.flush(); of.seek(0),你會做你想做的。

3

有一個文件指針,指向上一個寫入或讀取的位置。寫入of後,文件指針位於文件的末尾,因此無法讀取任何內容。

最佳,打開文件兩次,一次寫入和一次閱讀:

with open(args.infile, "r") as f, open(args.outfile, "w") as of: 
    for line in f: 
     of.write(line) 

with open(args.reference,"r") as rf: 
    for line in rf: 
     if line[0:3]== "TER": 
      resnum = line[22:27] 
      #resnum_1[resnum] = "TER" 

with open(args.outfile, "r") as of 
    for line in of: 
     if line [0:4]== "ATOM": 
      res = line[22:27] 
      if res == resnum: 
       print res 
1

第一循環之後,你寫的最後一行後of點文件點。當你嘗試從那裏讀取時,你已經在文件的末尾,所以沒有什麼可以循環。你需要回到開始。

with open(args.infile, "r") as f, open(args.outfile, "w+") as of, open(args.reference,"r") as rf: 
    for line in f: 
     of.write(line) 
    for line in rf: 
     if line[0:3]== "TER": 
      resnum = line[22:27] 
      #resnum_1[resnum] = "TER" 
    of.seek(0) 
    for line in of: 
     if line [0:4]== "ATOM": 
      res = line[22:27] 
      if res == resnum: 
       print res 
0

以前的答案提供了一些見解,但我喜歡乾淨/短碼和沖洗的併發症/求是不是真的需要:

resnum = '' 
with open(args.reference,"r") as reffh: 
    for line in reffh: 
     if line.startswith("TER"): 
      resnum = line[22:27] 

with open(args.infile, "r") as infh, open(args.outfile, "r") as outfh 
    for line in infh: 
     outfh.write(line) # moved from the first block 

     if line.startswith("ATOM"): 
      res = line[22:27] 
      if res == resnum: 
       print res