文件上的未绑定本地错误

时间:2014-08-29 14:07:14

标签: python python-2.7

我对此文件有疑问。当我启动它时,我在第24行得到一个错误。

UnboundLocal Error : local variable 'file_out' referenced before assignment.

任何关于如何纠正它的建议将不胜感激。我不得不说我是python上的一个完整的菜鸟,并没有自己写这个。

#!/usr/local/python

import sys, getopt
import os

usage="python correct_mol2.py -i 2qab_ligand.mol2 -o 2qab_ligand_new.mol2\n"

def main(argv):

    try:
        opts,args = getopt.getopt(sys.argv[1:],'hi:o:')
    except getopt.GetoptError:
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print usage
            sys.exit()
        elif opt == '-i':
                file_in = arg
        elif opt == '-o':
            file_out = arg
    x=0
    fout=file("%s"%file_out,"w")
    for line in file(file_in):
#       print line
        if line.find("@<TRIPOS>BOND") >= 0:
            x=0
        if x==0:
            fout.write(line)
        if x==1:
            if line[47:49] == '35' :
                fout.write(line[:47]+"Br"+line[49:])
                continue
            if line[47:49] == '17' :
                fout.write(line[:47]+"Cl"+line[49:])
                continue
            if line[47:48] == '9' :
                fout.write(line[:47]+"F"+line[48:])
                continue
            if (line[47] == 'H' and line[48] ==' ') or line[47] == 'F' or line[47:49] == 'Br' or line[47:49] == 'Cl' :
                fout.write(line)
                continue
            else:
                fout.write(line[:48]+"."+line[48:54]+line[55:])
        if line.find("@<TRIPOS>ATOM") >= 0:
            x=1
    fout.close()

main(sys.argv)

1 个答案:

答案 0 :(得分:1)

如果设置了file_out参数,则-o参数仅

您可能需要在for opt, arg in opts:循环之前设置默认值:

file_out = 'default_filename'

如果-o是强制性选项,则需要明确测试该选项是否缺席。

对您的代码的其他评论:

  • 改用argparse; optparse已被弃用,它的继承者更灵活,更灵活。

  • file_out在设置时已经是一个字符串。无需使用字符串格式;您可以直接将其传递给open()(而不是file(),也弃用)。如果您将文件对象用作context manager,那么它将自动关闭:

    with open(file_out, "w") as fout, open(file_in) as fin:
        for line in fin:
    
  • 您可以将文件对象用作迭代器,这意味着您可以在解析状态发生变化时推进文件对象并在for循环中获取更多行。用它来检测Tripos MOL2记录。

    Tripos MOL2 data records使用制表符或空格分隔线条;将您的行拆分为列,然后选择特定列以映射替换值。这比将线切割到特定列要脆弱得多:

    map = {'35': 'Br', '17': 'Cl', '9': 'F'}
    # when we encounter a mapped value, make it easier on ourselves
    # and map those back to themselves
    map.update((v: v) for v in map.values())
    
    section = None
    for line in fin:
        if line[0] == '@':
            # new section
            section = line.strip().rpartition('>')[-1]
            fout.write(line)
            continue
    
        if section != 'ATOM':
            fout.write(line)
            continue
    
        # parse the ATOM section
        for line in fin:
            if line[0] == '@':  # section end, we are done
                section = line.strip().rpartition('>')[-1]
                fout.write(line)
                break
    
            # atom data lines are whitespace separated
            row = line.split()
    
            # I'm assuming column 7 is the value you are replacing; adjust as required
            row[7] = map.get(row[7], '.')
    
            # re-join line with tabs, write out
            fout.write('\t'.join(row) + '\n')