簡體   English   中英

是否不遍歷文件?

[英]Doesnt iterate over the file?

我試圖在(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

有一個文件指針,指向最后寫入或讀取的位置。 寫入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

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

您想將數據刷新到磁盤,然后將指針移到文件的開頭:

# 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)

只需添加of.flush(); of.seek(0) of.flush(); of.seek(0)之前for line in of ,您將做自己想要的事情。

第一個循環后,該文件點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

先前的答案提供了一些見解,但我並不喜歡干凈/簡短的代碼,並且沖洗/查找的復雜性並不是真正需要的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM