定义infile - python

时间:2013-11-21 18:04:30

标签: python python-2.7

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

我整合了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)

我知道这是一个简单的问题,但我似乎无法看到我混淆了什么。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我遇到的问题绝对是由于缩进,与@msturdy在评论中提到的一致。但是,另一个问题是我在原始问题中没有包含的关键代码。该代码是程序函数的定义,它调用所有输入参数,然后在输入文件定义后再次重复。

请参阅上面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)