define infile - python



我编写了一个使用手动输入文件的代码。

我集成了with open(input) as input_file,以便直接从terminal调用所有需要的参数。

然而,我得到了以下"回溯":

Traceback (most recent call last):
  File "sumVectors.py", line 32, in <module>
    with open(classA_infile, "rb") as opened_infile_A:
NameError: name 'classA_infile' is not defined

这是定义infile的代码。关于我哪里出了问题,有什么线索吗?

def main(argv):
    try:
        opts, args = getopt.getopt(
            argv[1:], "hb:a:o:",
            ["help", "classB=", "classA=", "output="])
    except getopt.GetoptError as err:
        print str(err)
        usage()
        sys.exit(2)
    class_dictA = {}
    with open(classA_infile, "rb") as opened_infile_A:
        for line in opened_infile_A:
            items = line.split()
            print items

        for opt, value in opts:
            if opt in ("-h", "--help"):
                help_msg()
                usage()
                sys.exit()
            elif opt in ("-a", "--classA"):
                classA_infile = value
            else:
                assert False, "unhandled option"
        if len(opts) < 3:
            assert False, "an option is missing"
        program(classA_infile)

    if __name__ == '__main__':
        main(sys.argv)

我知道这是一个简单的问题,但我似乎看不出我把什么东西搞混了。谢谢你的帮助。

我遇到的问题完全是因为缩进,就像@mstudy在评论中提到的那样。然而,另一个问题是我在最初的问题中没有包括的一行关键代码。该代码是程序函数的定义,它调用所有输入参数,然后在定义输入文件后再次重复。

参见class_dictA = {}上方的行。由于没有包括这一行,我遇到了缩进问题,甚至没有意识到代码中存在根本错误。

def program(classA_infile): ### I included this line -- which required the rest of the script to be controlled for indentation.
    class_dictA = {}
    with open(classA_infile, "rb") as opened_infile_A:
        for line in opened_infile_A:
            items = line.split()
            print items
 for opt, value in opts:
            if opt in ("-h", "--help"):
                help_msg()
                usage()
                sys.exit()
            elif opt in ("-a", "--classA"):
                classA_infile = value
            else:
                assert False, "unhandled option"
        if len(opts) < 3:
            assert False, "an option is missing"
        program(classA_infile) ## here is where the `arg def` is called.

    if __name__ == '__main__':
        main(sys.argv)