不迭代文件?

2024-06-16 10:32:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: ofinforifas字母lineargs
3条回答

丹尼尔的回答给了你正确的理由,但是错误的建议。你知道吗

要将数据刷新到磁盘,然后将指针移到文件的开头:

# 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,你就可以随心所欲了。你知道吗

在第一个循环之后,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

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

相关问题 更多 >