我正在尝试将某些值与CSV文件中的diff时间进行比较。例如:iam搜索前27个字节的值并节省时间。然后第二个27的值和时间不同于第一个然后保存它的时间然后第三个等等。问题是当我尝试将时间保存到变量以将其与第二个相同的值进行比较时它给了我这个错误:
UnboundLocalError:赋值前引用的局部变量'T3' “
import csv
import os
import glob
class dot(object):
Time=""
Payload=""
Timediff=""
global T1
global T2
global T3
global T4
def searchfunc():
path = '/Users/mohamedshaaban/Downloads/tes/Camera'
for infile in glob.glob( os.path.join(path, '*csv') ):
with open(infile) as inf:
reader = csv.reader(inf)
partname = partsize = None
partname2 = partsize2 = None
partname3 = partsize3 = None
partname4 = partsize4 = None
partname5 = partsize5 = None
camera = dot()
camera.Payload1='30 bytes'
camera.Payload2='27 bytes'
camera.Payload3='17 bytes'
camera.Payload4='5 bytes'
camera.Payload5='6 bytes'
for row in reader:
if camera.Payload1 in row[2] and partname is None:
x = row[2]
partname = x[0:-1]
T1 = float(row[4])
if camera.Payload2 in row[2] and partname2 is None:
x2 = row[2]
partname2 = x2[0:-1]
T2 = float(row[4])
#print partname2
#print Time2
if camera.Payload2 in row[2] and partname3 is None:
if float(row[4]) != T2:
T3 = float(row[4])
x3 = row[2]
partname4 = x3[0:-1]
print partname3
if camera.Payload2 in row[2] and partname4 is None:
if float(row[4]) != T3:
T4 = float(row[4])
x4 = row[2]
partname4 = x4[0:-1]
print partname3
print Time5
searchfunc()
答案 0 :(得分:1)
您正在错误地使用全局变量 - 在函数内部使用global
修饰符来指示该变量具有全局读/写权限。然而,
永远不会在某些执行路径上设置T3
,因此您会收到此错误。
您希望您的设置具有以下形式:
T1 = None # or your preferred initial value
T2 = None
T3 = None
T4 = None
def searchfunc():
global T1, T2, T3, T4
但是,请注意,尽可能避免使用全局变量。 Globals本质上是糟糕的编程风格和实践。 this answer to "Why are global variables evil?"中有一些很棒的链接。
答案 1 :(得分:0)
您需要在函数内声明变量为全局变量。否则python假定它只在本地范围内。
尝试在你的函数声明下添加它(也将vars声明在外部作用域中声明:
def searchfunc():
global T1, T2, T3, T4