Home > Net >  Iterating over folder names in Python
Iterating over folder names in Python

Time:09-12

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:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept12_2022\Test.py", line 12, in <module>
    df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols="A,C:AA")

  File "C:\Users\USER\anaconda3\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
    return func(*args, **kwargs)

  File "C:\Users\USER\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 364, in read_excel
    io = ExcelFile(io, storage_options=storage_options, engine=engine)

  File "C:\Users\USER\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 1191, in __init__
    ext = inspect_excel_format(

  File "C:\Users\USER\anaconda3\lib\site-packages\pandas\io\excel\_base.py", line 1070, in inspect_excel_format
    with get_handle(

  File "C:\Users\USER\anaconda3\lib\site-packages\pandas\io\common.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'

CodePudding user response:

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

  • Related