2012-10-30 43 views
-2

(另一个begynner问题)用绳子

我需要提取一些清单,值从几个txt文件(每个文件两个列表)更改列表名称。 我做了一个函数来提取我需要的值,但我不知道如何命名列表,以便它们包含原始文件的名称。例如:

文件名+“‘+测量 文件名+’” +日期

的第一个问题是,这些名字是字符串,我不知道如何将它们转换成列表的名称。

第二个问题是,这样做到一个函数的名称不是全局的,我以后不能访问列表。如果我在变量的名称前写入全局变量,则会出现错误。

def open_catch_down(): 

    file = raw_input('Give the name of the file:') 

    infile = open(file,'r') 
    lines = infile.readlines() 
    infile.close() 

    global dates 
    global values 
    dates = [] 
    values = [] 


    import datetime 

    for line in lines[1:]: 
     words = line.split() 
     year = int(words[0]) 
     month = int(words[1]) 
     day = int(words[2]) 
     hour = int(words[3]) 
     minute = int(words[4]) 
     second = int(words[5]) 
     date = datetime.datetime(year,month,day,hour,minute,second) 
     dates.append(date) 
     value = float(words[6]) 
     values.append(value) 

    vars()[file + '_' + 'values'] = values 


open_catch_down() 

print vars()[file + '_' + 'values'] 

然后我得到的错误:

print vars()[file + '_' + 'values'] 

类型错误:不支持的操作数类型(S)为+: '型' 和 '海峡'

+0

我们需要更多的信息,比如你甚至没有列出您正在使用的语言或环境英寸 – asawyer

+0

你是否要重新命名一个变量?许多语言不会让你这样做。仍然不确定你在使用什么语言,但只是把变量放在变量的前面不会总是这样做,你需要查看这些语言范围方法。 –

+0

对不起,这是Python – user1785070

回答

1

首先,你的vars用法是错误的,没有参数,它只是返回不可写的locals字典。您可以改用globals

我们您的例外......在file变量是不是在你的打印语句的范围:

def open_catch_down(): 
    file = raw_input(...) #this variable is local to the function 
    [...] 

print file    #here, file references the built-in file type 

由于file是内置式的文件处理蟒蛇的名称,在file print语句引用这个类,这会导致错误。如果您将filename命名为filename而不是file(您应该这样做,因为阴影内置名称总是一个坏主意),您将得到一个UnboundLocalError。为您列举了最简单的解决办法是让你的函数返回的文件名,并将其保存在外部范围:

def open_catch_down(): 
    filename = raw_input(...) #your file name 

    #... rest of the code 

    return filename 

filename = open_catch_down() 
print filename