Home > Net >  Why os.listdir() finds the excel but pd.read_excel() returns error?
Why os.listdir() finds the excel but pd.read_excel() returns error?

Time:07-22

here is the simple version of my code:

for filename in os.listdir('excels/'):
    print(filename)
    df = pd.read_excel(filename)
    df.head()

Output is:

RandomExcelData.xlsx
---------------------------------------------------------------------------
FileNotFoundError: [Errno 2] No such file or directory: 'RandomExcelData.xlsx'

What is really happening here? why pandas does not recognize the file name that is clearly there?

I tested this and it works properly:

df = pd.read_excel('excels/RandomExcelData.xlsx')
df.head()

this returns output as intended...

CodePudding user response:

You need to add the path when reading the Excel files:

for filename in os.listdir('excels/'):
    print(filename)
    df = pd.read_excel('excels/'   filename)
    df.head()

CodePudding user response:

You are getting this result because filename is just the filename, not the full path. Try this line instead:

df = pd.read_excel('excels/'   filename)

Or, change the script's working directory to 'excels':

for filename in os.listdir('excels/'):
    print(filename)
    os.chdir('excels')
    df = pd.read_excel(filename)
    df.head()

CodePudding user response:

directory = 'data/'

files = [os.path.join(directory, file) for file in os.listdir(directory) if file.endswith('.csv')]

for file in files:
    df = pd.read_csv(file)
  • Related