Adapting path/directory to different users in python

Question:

I have an Excel file saved on a share point. I would like that every users who has access to the file can run the python code automatically. The code looks like this:

df = pd.read_excel(r'C:Usersusernamefile path')

I would like to replace the username with the names of the user. So for example Martin would have

df = pd.read_excel(r'C:UsersMartinfile path')

So far I got:

user = easygui.enterbox('Please insert your username')

df = pd.read_excel(r'C:Users{user}file path')
``
Asked By: Lisa

||

Answers:

A possible solution:

df = pd.read_excel(fr'C:Users{user}file path')
Answered By: PaulS

You probably want pathlib.Path.home():

from pathlib import Path

excel_path = Path.home() / "path" / "filename.xlsx"
df = pd.read_excel(str(excel_path))
Answered By: brunns
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.