2012-05-27 216 views
0

我正在玩cgi(上傳文件格式),存儲for循環迭代數據

我正在接收文件作爲存儲對象,我把它放在(輸入)變量中。

這是簡單的迭代。

for file in input: 
    filepath = .... 
    filename, fileext = os.path.splitext(filepath) 
    file_real_name = .... 
    file_size = .... 
    file_type = ... 
    file_url = .... 
    file_short_name = ... 
    file_show_link = .... 

    # etc 

如果只有一個文件,它會很容易,但是如果我有多個文件?

我怎麼能有保存所有

uploaded_files在那裏我可以與所有的信息,上述迭代訪問每個上傳的文件迭代信息的另一個值?

我想閱讀的文檔,但我不能換我的頭周圍的一些迭代概念呢,不好意思:)

+1

嘗試詞典的列表 –

+0

@Alex謝謝你,一個例子會很棒。 – static

回答

1

你想用一個數據結構來保存數據。根據不同的複雜性,你可能想簡單地使用字典列表:

files = [] 
for file in input: 
    files.append({ 
     "path": get_path(file), 
     "name": get_name(file), 
     "size": get_size(file), 
     ... 
    }) 

或者,如果你發現你需要對你的數據進行大量的操作,你可能想使自己的類,並作出對象列表:

class SomeFile: 
    def __init__(self, path, name, size, ...): 
     self.path = path 
     ... 

    def do_something_with_file(self): 
     ... 

files = [] 
for file in input: 
    files.append(SomeFile(get_path(file), get_name(file), get_size(file), ...)) 

注意,在這裏,你是繼迭代的迭代器建立一個列表的模式。爲此,您可以使用list comprehension高效,e.g:

[{"path": get_path(file), "name": get_name(file), ...} for file in input] 

還要注意的是fileinput是非常糟糕的變量名,因爲它們會掩蓋內建file()input()

+0

謝謝,get_path()是我必須定義的方法嗎? – static

+0

@static它只是佔位符代碼 - 你可以放置任何你想要的代碼來生成你需要的值。 –

+0

太好了,非常感謝你的詳細解答。 – static

0
results = [] 
for i in range(5): 
    file_data = {} 
    file_data['a'] = i 
    file_data['b'] = i**2 
    results.append(file_data) 
print results 
+0

謝謝你試圖幫助。 – static