As mentioned in the comments, it's not a good idea to dynamically create list names in a loop. Instead, you should use a collection like a list or dictionary to save your lists. I'll show how to do that below.
I also mentioned that doing this sort of thing won't work:
for i in list_ot:
for row in reader:
On the first run of the outer for i in list_ot:
loop we read through the whole file in the inner for row in reader:
loop. And then when we get to the second run of the list_ot
loop the file cursor will still be at the end of the file, so there will be no data left to read, and the inner loop will finish immediately. We could reset the file cursor to the start of the file, using the file's .seek
method, but it's better to avoid re-reading the same file data multiple times.
Instead, when we read a row, we need to check if its 'ot' field matches one of the values in list_ot
, and if it does we can save the row into the appropriate list.
The code below shows how to save your data into a dictionary of lists. Please study it carefully! This code was designed to run on Python 3, but it should also run correctly on Python 2 (although strictly speaking you should open the CSV file in binary mode in Python 2).
The csv.DictReader
yields an OrderedDict
of each row that it reads. This can be handy if you need to preserve the order of the fields in the row, but if you don't need to preserve the order then you can easily convert the OrderedDict
to a plain dict
, which is what m code does when it saves a row into the mylists
dictionary.
import csv
list_ot = [123, 234, 774, 539, 492, 556]
# Create a dict of empty lists, with the numbers in list_ot as the keys
mylists = {k: [] for k in list_ot}
with open('data', 'r') as f:
reader = csv.DictReader(f, skipinitialspace=True)
for row in reader:
print(row)
ot = int(row['ot'])
if ot in mylists:
mylists[ot].append(dict(row))
print()
for k in list_ot:
print(k, mylists[k])
output
OrderedDict([('Sin', '1'), ('ot', '123'), ('cant', '999')])
OrderedDict([('Sin', '12'), ('ot', '234'), ('cant', '888')])
OrderedDict([('Sin', '23'), ('ot', '123'), ('cant', '768')])
OrderedDict([('Sin', '22'), ('ot', '774'), ('cant', '442')])
123 [{'Sin': '1', 'ot': '123', 'cant': '999'}, {'Sin': '23', 'ot': '123', 'cant': '768'}]
234 [{'Sin': '12', 'ot': '234', 'cant': '888'}]
774 [{'Sin': '22', 'ot': '774', 'cant': '442'}]
539 []
492 []
556 []