FaCoffee
FaCoffee

Reputation: 7929

On using a string as an integer counter (aka index) in a for loop

I have a folder with n csv files. They are accessed and read in a for loop like this:

#do stuff
for file in os.listdir(directoryPath):
    if file.endswith(".csv"):
       #do stuff

Outside of the for loop are a number of numpy arrays initialized to zero. Each array has to carry a specific value located in the current csv file.

My question: is it possible to use file, which I assume is a string, as an integer, in order to fill my arrays for instance like this: array1[file]=numpy.genfromtxt(file,delimiter=',')[:,2]?

I am afraid this very line does not work as file cannot be treated like an integer, so how would you deal with this? Thank you!

Upvotes: 0

Views: 47

Answers (1)

Will Vousden
Will Vousden

Reputation: 33378

You could use enumerate, which generates tuples that pair the index of an item with the item itself:

for i, file in enumerate(os.listdir(directoryPath)):
    if file.endswith(".csv"):
       array1[i] = numpy.genfromtxt(file, delimiter=',')[:,2]

Or you could store the Numpy arrays in a dictionary that is indexed directly by the associated file name:

arrays = {}
for file in os.listdir(directoryPath):
    if file.endswith(".csv"):
       arrays[file] = numpy.genfromtxt(file, delimiter=',')[:,2]

Or with an OrderedDict:

from collections import OrderedDict

arrays = OrderedDict()
for file in os.listdir(directoryPath):
    if file.endswith(".csv"):
       arrays[file] = numpy.genfromtxt(file, delimiter=',')[:,2]

Upvotes: 1

Related Questions