Search code examples
pythonloopsfor-loopread-csv

Using a for loop with two variables in Python


I want to use two variables in a loop. Currently, I am running into an error using the following code; The filenames generally contain four column (time, power, time, power) with a lot of rows (up to 1000).

filename = [filename1, filename2, filename3, filename4, filename5]
n = len(filename)
for i, j in range(n):
    df = pd.read_csv(filename[i], delim_whitespace=True,skiprows=4, encoding='latin1') # [0] = filename1
    Time = df[j].iloc[:,0]
    Power = df[j].iloc[:,1]
    Time1 = df[j].iloc[:,2]
    Power1 = df[j].iloc[:,3]
    print("power", Time1)

There are multiple filenames (currently 5 but I might use more, hence "n". The filenames should be implemented in the df = row. Then, below I want to extract separate columns from each file, therefore I want to use the "Time = df[j].iloc[:,0] lines. However, this does not work:

TypeError: cannot unpack non-iterable int object

How can I adjust the code so that it works?


Solution

  • The for loop just unpacks the values you give it. So in this case range(n) only returns a single int. If you want to unpack multiple values you need to give it something else like a zip/enumerate builtin function which creates tuples.

    To fix this error you need to remove the i, from the for loop.

    Or skip getting the length of the list and use for i, df in enumerate(filename).