全局名称'行'未定义

时间:2018-01-26 19:47:27

标签: python python-2.7 scope

我正在编写一个函数来读取给定目录中的文件中的数据但是遇到了作用域问题

def get_json_file(content_type, proc_date):
    filenames = glob.glob('/home/*')
    with open('/home/tgfile', 'w') as outfile:
            for fname in filenames:
                    print ('line 1..')
                    with open(fname) as infile:
                            print ('line 2..')
                            with line in infile:
                                    print ('line 3..')
                                    outfile.write(line)
get_json_file('dir', '20180122')

以下是错误消息:

  

文件“gen_json_file.py”,第17行,in       get_json_file('SENTIMENT_ANNOTATION','20180122')     在get_json_file中的文件“gen_json_file.py”,第12行       在infile中使用line:   NameError:未定义全局名称'line'

I程序输出第1行,第2行调试语句但在outfile.write(行)处失败。我将'line'变量声明为全局,但这没有帮助。

1 个答案:

答案 0 :(得分:1)

@Mark Dickinson的评论是正确的,您可以在with for使用def get_json_file(content_type, proc_date): filenames = glob.glob('/home/*') with open('/home/tgfile', 'w') as outfile: for fname in filenames: print ('line 1..') with open(fname, 'r') as infile: print ('line 2..') for line in infile: print ('line 3..') outfile.write(line) get_json_file('dir', '20180122')

为了清晰起见,您可能还想明确打开输入文件

.horizontal {
    background: gray;
    height: 640px;
    margin: 0px;
    padding: 0px;
    width:100%;
    display:flex;
    flex-wrap: wrap;
    flex-direction: column;
}