不遍历文件?

Doesnt iterate over the file?

我试图在 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

有一个文件指针,指向最后写入或读取的位置。写入 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

第一次循环后,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

Daniel 的回答给了你正确的理由,但错误的建议。

您想将数据刷新到磁盘,然后将指针移至文件开头:

# 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),您就可以为所欲为了。

之前的答案提供了一些见解,但我喜欢干净/简短的代码,并不需要复杂的冲洗/查找:

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