2013-01-04 77 views
0

Guyz,我遇到了以下错误与belwo代码,哪里出错? 任何清理建议,也接受以下UnboundLocalError:分配之前引用的局部变量'文件'

for line in file(timedir + "/change_authors.txt"): 
UnboundLocalError: local variable 'file' referenced before assignment 

代码:

import os,datetime 
    import subprocess 
    from subprocess import check_call,Popen, PIPE 
    from shutil import copyfile,copy 

def main(): 
    #check_call("ssh -p 29418 review-droid.comp.com change query --commit-message status:open project:platform/vendor/qcom-proprietary/radio branch:master | grep -Po '(?<=(email|umber):)\S+' | xargs -n2") 
    global timedir 
    change=147441 
    timedir=datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') 
    #changeauthors = dict((int(x.split('/')[3]), x) for line in file(timedir + "/change_authors.txt")) 
    for line in file(timedir + "/change_authors.txt"): 
     changeauthors = dict(line.split()[0], line.split()[1]) 
    print changeauthors[change] 
    try: 
     os.makedirs(timedir) 
    except OSError, e: 
     if e.errno != 17: 
      raise # This was not a "directory exist" error.. 
    with open(timedir + "/change_authors.txt", "wb") as file: 
     check_call("ssh -p 29418 review-droid.comp.com " 
      "change query --commit-message " 
      "status:open project:platform/vendor/qcom-proprietary/radio branch:master |" 
      "grep -Po '(?<=(email|umber):)\S+' |" 
      "xargs -n2", 
       shell=True, # need shell due to the pipes 
       stdout=file) # redirect to a file 

if __name__ == '__main__': 
    main() 

回答

1

您不应该使用file()在您的文件系统上打开文件:使用open(在导致错误的行上)。


文档recommends against it

Constructor function for the file type, described further in section File Objects. The constructor’s arguments are the same as those of the open() built-in function described below.

When opening a file, it’s preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)).

New in version 2.2.

而且,它会走在Python 3

+0

谢谢,是行Gerritauthors = Dict(line.split()[0],line.split()[1])有问题..基本上我试图根据空间拆分每一行并保存第一个字符串作为索引,第二个字符串作为元素... – user1927396

+0

@ user1927396您可以做'index,element = line.split('',1)'来实现这一点。 –

+0

如果我这样做,我不断得到TypeError:预计最多1个参数,在行changeauthors = dict(索引,元素)得到2 – user1927396

3

这是功能范围做。随着你的主函数稍后定义了它自己的文件变量,那么内置的文件函数就会被破坏。因此,当你最初尝试调用它时,它会抛出这个错误,因为它为自己保留了本地文件变量。如果你要从主函数中取出这些代码,或者用open()语句将后面的引用改为'file',它应该可以工作。

不过,我会做以下...

相反的:

for line in file(timedir + "/change_authors.txt"): 

你应该使用:

for line in open(timedir + "/change_authors.txt", 'r'): 

open() function应该用于返回一个文件对象,是优选地为file()

+0

它实际上是文件,我不知道如何在它之前的工作,我有一个脚本,用于线路在文件()的作品 – user1927396

相关问题