Handling usernames in file paths using Python

1k views Asked by At

I'm writing a program that I would like to make a stand alone for my company. It works perfectly when I run it from the sublime text shell and I have everything set up to go except one issue that I can't seem to solve; file paths that involve usernames. Does anyone have any suggestion on how to handle this?

An example is wb.save(r'C:\Users******\Desktop\Excel.xlsx')

I want to make the ****** part either be automatic or an input box.

3

There are 3 answers

1
Duncan On BEST ANSWER

Use os.path.expanduser() with '~' where you want the home directory:

import os
print(os.path.expanduser('~/Desktop/Excel.xlsx'))

Alternatively use pathlib.Path:

from pathlib import Path
print(Path.home() / 'Desktop' / 'Excel.xlsx')
0
Ochmar On

os.getlogin() will do

import os
path = os.path.join(r'C:\Users',os.getlogin(),'Desktop','Excel.xlsx')
print(path)
0
aaron On

Awesome! Looks like that worked but it presented another error now when I create it as a stand alone.

Wait originally works when I run it from the shell using this code, where EC is expected conditions:

wait.until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_name('AppBody')))   

Whenever I run it as a stand alone though I get the following error:

Traceback (most recent call last):
  File "Stand_Alone_CAS_Automation", line 57, in <module>
NameError: name 'wait' is not defined
[17344] Failed to execute script Stand_Alone_CAS_Automation