0

I would like to read the excel files in directory if there is a file with specific name And then do some data related operations. But firstly I have a problem to read the files with pandas

import os
import pandas as pd

for filename in os.listdir(my_path):
    if filename.startswith('PB orders Dec'):
        dec=pd.read_excel(filename,sheet_name='Raw data')

error: FileNotFoundError: [Errno 2] No such file or directory: 'PB orders December.xlsb'

But when I run this code:

import os
import pandas as pd
    
    for filename in os.listdir(my_path):
        if filename.startswith('PB orders Dec'):
        print(filename)

result is the existing file name in directory : PB orders December.xlsb

How can I read a specific file in directory based on the name?

0

2 Answers 2

1

The directory is missing when you read_excel, you only point to the file as you showed with the print.

You need to rebuild the full path with for instance, os.path.join:

import os
import pandas as pd

for filename in os.listdir(my_path):
    if filename.startswith('PB orders Dec'):
        dec = pd.read_excel(os.path.join(my_path, filename), sheet_name='Raw data')
Sign up to request clarification or add additional context in comments.

Comments

1

Add the directory: path = os.path.join(my_path, filename), then pd.read_excel(path, ...):

import os
import pandas as pd

for filename in os.listdir(my_path):
    if filename.startswith('PB orders Dec'):
        path = os.path.join(my_path, filename)
        dec = pd.read_excel(path, sheet_name='Raw data')

2 Comments

after installing fsspec, i get new error OSError: File contains no valid workbook part
it is the extension problem. with xlsx it works but with xlsb no

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.