Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading