Issue with creating a pandas dataframe if filepath is a variable

Viewed 24

I am using a code that browse through a selected folder and checks for the files that contain a specific string. When a file is found, it creates an absolute path to pass it to a pandas data-frame.

for file in os.listdir(files_path):
   if str_tr in file:
      path= os.path.abspath(file)
      df[ctr] = pd.read_excel(path)

In this case the full path is : enter image description here But when I try to pass it to pandas I receive error :

[Errno 2] No such file or directory: enter image description here I think because of double slashes. What can I do to fix it? Normally if it was a string I would use 'r' but in my case the path is in a variable.

1 Answers

I think you neer to add r to the path before giving it to pandas:

for file in os.listdir(files_path):
    if str_tr in file:
    path= rf'{os.path.abspath(file)}' 
    df[ctr] = pd.read_excel(path)
Related