Ayed
Ayed

Reputation: 383

storing for loop iteration data

I am playing with cgi (uploading file form),

and I am receiving the files as storage object and I sotred it in (input) variable.

this is the simple iteration.

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

it would be easy if it was only one file , but what If i have more than one ?

how can I have another value that holds all the iteration information in

like uploaded_files where I can access each uploaded file with all the information for the above iteration ?

I tried to read the docs but I cant wrap my head around some iteration concepts yet, sorry :)

Upvotes: 0

Views: 5538

Answers (2)

Gareth Latty
Gareth Latty

Reputation: 88977

You want to use a data structure to hold your data. Depending on the complexity, you may want to simply use a list of dictionaries:

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

Or, if you find you need to perform lots of operations on your data, you might want to make your own class and make a list of objects:

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), ...))

Note that here you are following a pattern of building up a list by iterating over an iterator. You can do this efficiently using a list comprehension, e.g:

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

Also note that file and input are really bad variable names, as they will mask the builtins file() and input().

Upvotes: 1

Alex L
Alex L

Reputation: 8925

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

Upvotes: 0

Related Questions