【问题标题】:Global Name 'line' not defined [closed]未定义全局名称“行”[关闭]
【发布时间】:2018-01-26 19:47:26
【问题描述】:

我正在编写一个函数来从给定目录中的文件中读取数据,但遇到了范围问题

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 行,在 get_json_file('SENTIMENT_ANNOTATION', '20180122') 文件“gen_json_file.py”,第 12 行,在 get_json_file 在 infile 中有一行: NameError: 未定义全局名称'line'

I 程序输出第 1 行、第 2 行调试语句,但在 outfile.write(line) 处失败。我将“line”变量声明为全局变量,但这无济于事。

【问题讨论】:

  • for line in infile:替换with line in infile:
  • 太棒了..它成功了!!您能评论一下吗,我可以将其标记为正确答案

标签: python python-2.7 scope


【解决方案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')

【讨论】:

  • 没错..它奏效了!
猜你喜欢
  • 1970-01-01
  • 2013-06-20
  • 1970-01-01
  • 2018-05-04
  • 2015-12-22
  • 2014-04-18
  • 2015-08-08
  • 2011-04-27
  • 2013-09-04
相关资源
最近更新 更多