1

所以我的代码工作正常,但它不仅会打印出一半的正确结果。我正在尝试将标题写入文件。我已经检查并打印了计算,这是正确的。但是,我只打印了一个正确编号的文件,而没有打印出另一个文件。

lookup[uniprotID] =['177','26','418']

没有正确打印出来的文件有这个信息:start 174 and end 196

该文件应具有以下结果:

uniproID | 在 3 位置

YSADACERD

这是我的代码。

for i, (start, end) in enumerate(searchPFAM(fname)):

    print start, end
    for item in lookup[uniprotID]:
        item, start, end = map(int, (item, start, end))

        if start <=end:
            if item in xrange(start, end+1):
                print item
                with open('newfile-%s.txt' % i,'w') as fileinput:
                    atPosition = (item)-start
                    result = str(atPosition)
                    fileinput.write(">"+uniprotID+' | at '+result +' position\n')
                    text=''.join(makeList[(start-1):(end)])
                    fileinput.write(text)
            else:
                with open('newfile-%s.txt' % i,'w') as fileinput:
                    fileinput.write(">"+uniprotID+' | '+ 'N/A\n')

                    text=''.join(makeList[(start-1):(end)])
                    fileinput.write(text)
4

2 回答 2

1

Perhaps the problem is that open('newfile-%s.txt' % i,'w') opens a file for writing, overwriting any existing file of that name. If that's the problem, try opening it for appending open('newfile-%s.txt' % i,'a').

于 2012-07-13T19:24:50.527 回答
0

正如 MRAB 所说,您很有可能多次覆盖同一个文件。with将块拉出for item in lookup[...]块以确保文件不会被覆盖。请注意,如果多个项目lookup[unitProtID]与 if 条件匹配,则该文件将被多次写入。

for index, (start, end) in enumerate(searchPFAM(fname)):
    with open('newfile-%s.txt' % index,'w') as fileinput:
        print start, end
        for item in lookup[uniprotID]:
            item, start, end = map(int, (item, start, end)) #You shouldn't be doing this here, you should convert these variables to ints when you first store them in "lookup".
            if start <= item <= end:
                print item
                result = str(item - start)
                fileinput.write(">{0} | at {1} position\n".format(uniprotID, result))
                fileinput.write(''.join(makeList[start-1:end]))
                break #exit loop, move onto next file.
        else:
                fileinput.write(">{0} | N/A\n".format(uniprotID))
                fileinput.write(''.join(makeList[start-1:end]))

如果这仍然给您带来问题,我建议您替换fileinput.write(...)with的每个实例print ...,并查看您的输出内容。

于 2012-07-13T20:05:35.607 回答