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?
CodePudding user response:
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')
CodePudding user response:
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')