Skip to content
Advertisement

How to loop through a folder in Python

I am a new python user and I am trying to loop through all the items in a set file. Here is my code this far –

import os
import pandas as pd
print(os.getcwd())


for files in os.listdir(r"../Python/Rev Renewables/Inputs/Option Inputs/"):
    file = pd.read_excel(files,sheet_name='ContractSpecs')
    print(file)

When I load the for loop without the pd.read_excel it prints the names of each of the sheets in the console yet when I add in the read_excel portion I receive an error stating “FileNotFoundError: [Errno 2] No such file or directory: ‘O2.LS Power SP15 Option-EY.xlsx'” I am not sure why it is able to locate the file and the correct name yet when it attempts to print to excel it can’t locate the file name even when they are identical.

Thank you

Advertisement

Answer

os.listdir in python lists all the files in a given directory you probably should give the entire path to pd.read_excel

import os
import pandas as pd
print(os.getcwd())
path = r"../Python/Rev Renewables/Inputs/Option Inputs/"

for files in os.listdir(path):
    file = pd.read_excel(path+files,sheet_name='ContractSpecs')
    print(file)


User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement