Iterating over folder names in Python

Question:

I have two folders, 1 and 2. I want to go to each folder which has the file Test.xlsx. I tried to iterate on file_loc using i in range(1,3) but there’s an error. The code works if I mention 1 or 2 on file_loc.

import pandas as pd
import numpy as np

for i in range(1,3):
    file_loc = "C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept12_2022\i\Test.xlsx"
    df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols="A,C:AA")
    A=df["N"].to_numpy()
    print([A])
    A = [x for x in A if str(x) != 'nan']
    print(A)
    A = [eval(e) for e in A]
    print(A)

    A=np.array(A)
    print([A])


    A_mean=[]
    for i in range(0,len(A)):
        A_mean.append(np.mean(A[i]))
    print(*A_mean, sep='n')

The error is

Traceback (most recent call last):

  File "C:UsersUSEROneDrive - TechnionResearch_TechnionPython_PNMSept12_2022Test.py", line 12, in <module>
    df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols="A,C:AA")

  File "C:UsersUSERanaconda3libsite-packagespandasutil_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)

  File "C:UsersUSERanaconda3libsite-packagespandasioexcel_base.py", line 364, in read_excel
    io = ExcelFile(io, storage_options=storage_options, engine=engine)

  File "C:UsersUSERanaconda3libsite-packagespandasioexcel_base.py", line 1191, in __init__
    ext = inspect_excel_format(

  File "C:UsersUSERanaconda3libsite-packagespandasioexcel_base.py", line 1070, in inspect_excel_format
    with get_handle(

  File "C:UsersUSERanaconda3libsite-packagespandasiocommon.py", line 711, in get_handle
    handle = open(handle, ioargs.mode)

FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept12_2022\i\Test.xlsx'
Asked By: user19862793

||

Answers:

for i in range(1,3):
    file_loc = f"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept12_2022\{i}\Test.xlsx"
    ...

Make sure you entered correct path

Answered By: Deven Ramani
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.