0

I have multiple filepaths in my code like such:

pd.read_excel(r'..\\..\\folder1 name\\folder2 name\\file.xlsx')

If someone else runs this on their computer, will it correctly function, given that they have access to the same filepath? The reason why I am doing this is because the files are on OneDrive. The path is the same for everyone, but everyone has a different user ID at the beginning i.e.

(r'userID\\..\\folder1 name\\folder2 name\\file.xlsx')
MontyP
  • 61
  • 9
  • 2
    If `file.xlsx` exists at that relative path and they run the python script from the directory the script is in, then yes. This is the exact reason relative paths are a thing – Pranav Hosangadi Nov 18 '20 at 18:42
  • 1
    Use ```%userprofile%```. Also view this https://stackoverflow.com/questions/2668909/how-to-find-the-real-user-home-directory-using-python – krmani Nov 18 '20 at 18:43
  • @Infinyte7 - True, keeping in mind that syntax is only valid on Win. – S3DEV Nov 18 '20 at 18:47
  • @PranavHosangadi Thank you! I only exclusively saw pathlib being suggested in answers, but my above solution seems simple enough to do the trick. – MontyP Nov 18 '20 at 19:37

1 Answers1

1

I think it's better to use python's pathlib (Python 3.4 or later) library.

from pathlib import Path
base_dir = Path(__file__).resolve().parent.parent
file_path = base_dir.joinpath("folder1 name", "folder2 name", "file.xlsx")

pd.read_excel(file_path)
belal_bh
  • 151
  • 6