伙计,我在下面的代码中遇到了下面的错误,哪里出了问题?也接受任何清理建议。
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()发布于 2013-01-04 08:11:02
不应该使用file()打开文件系统上的文件:使用open (在导致错误的行上)。
文档recommends against it
文件类型的
构造函数,在文件对象一节中进一步描述。构造函数的参数与下面描述的open()内置函数的参数相同。
当打开一个文件时,最好使用open()而不是直接调用这个构造函数。文件更适合于类型测试(例如,写入isinstance(f,file))。
版本2.2中的新功能。
此外,它在Python 3中也将消失。
发布于 2013-01-04 08:10:54
这与函数作用域有关。由于您的main函数稍后定义了自己的文件变量,因此内置的file函数将被销毁。因此,当您最初尝试调用它时,它会抛出此错误,因为它已经为自己保留了本地文件变量。如果您将此代码从main函数中删除,或者在with open()语句中将后面的引用更改为'file‘,那么它应该可以工作。
然而,我会做以下事情……
而不是:
for line in file(timedir + "/change_authors.txt"):您应该使用:
for line in open(timedir + "/change_authors.txt", 'r'):open() function应该用于返回文件对象,并且比file()更可取。
https://stackoverflow.com/questions/14149300
复制相似问题