使用 Python 处理文件路径中的用户名

Handling usernames in file paths using Python

我正在编写一个程序,我想为我的公司制作一个独立的程序。当我从 sublime 文本 运行 中 shell 并且我已经准备好一切,除了一个我似乎无法解决的问题外,它工作得很好;涉及用户名的文件路径。有人对如何处理这个问题有什么建议吗?

一个例子是 wb.save(r'C:\Users******\Desktop\Excel.xlsx')

我想把 ****** 部分设为自动或输入框。

os.getlogin() 会做

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

在您想要主目录的位置使用带有“~”的os.path.expanduser()

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

或者使用 pathlib.Path:

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

太棒了!看起来可行,但当我将其作为独立项目创建时,它现在又出现了另一个错误。

当我 运行 它从 shell 使用此代码时等待最初工作,其中 EC 是预期条件:

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

每当我 运行 它作为一个独立的,虽然我得到以下错误:

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