简体   繁体   中英

read the excel file in directory using pandas python

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?

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')

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM