不迭代文件?

时间:2017-05-10 19:15:53

标签: python python-2.x

我试图找到以字母ATOM开头的outfile(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"
    for line in of:
        if line [0:4]== "ATOM":
            res = line[22:27]
            if res == resnum:
                print res

4 个答案:

答案 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 :(得分: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)

只需在of.flush(); of.seek(0)之前添加for line in of,即可按照自己的意愿行事。

答案 2 :(得分: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

答案 3 :(得分: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