2012-07-13 53 views
1

所以我的代码工作正常,但它不会打印出正确结果的一半。 我想写一个头文件。我已检查并打印出计算结果,这是正确的。但是,我只有一个文件正确打印出正确的数字,并没有得到另一个文件打印出来。与列表字典和值有关的文件输出错误

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

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

这个文件应该有这个结果:

uniprotID |在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) 
+1

'如果项目在xrange(开始,结束+ 1):'应该编码'如果开始<=项目<=结束:' – mgilson 2012-07-13 19:35:15

回答

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

如果这仍然给你的问题,我建议你print ...取代的fileinput.write(...)每个实例,看看你的输出怎么说。

+0

现在我有几次覆盖它的问题。有没有一种方法可以在查找之前查看列表中的任何列表是否匹配 – 2012-07-13 20:22:49

+0

您的代码中包含“print item”语句。每次打印项目时,这都是来自'lookup'的匹配。 – 2012-07-13 20:27:03

+0

@ChadD:看我的编辑。第一场比赛后,代码将停止写入相同的文件。 – 2012-07-13 20:58:13

1

问题也许是open('newfile-%s.txt' % i,'w')打开用于写入的文件,覆盖该名称的任何现有文件。如果这是问题,请尝试打开它以追加open('newfile-%s.txt' % i,'a')

+0

你是对的a但是有没有办法阻止它重写文件后,它发现它的价值/计算 – 2012-07-13 20:10:23