Pythonos.path.exists存在(r“%SystemDrive%\Users\{username}\Documents”)

2024-09-29 01:30:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我要这个程序自动检查文件是否存在。我想要一种方法让它总是检查当前用户的文档文件夹。 if os.path.exists(r"%SystemDrive%\Users\{username}\Documents\QQOutput.bas"): 所以目标始终是当前登录的用户,我不必不断更改不同用户的代码等等,我不想为不同的用户/目录创建多个python文件。你知道吗

import keyboard
import time
import ctypes

def Mbox(title, text, style):
    return ctypes.windll.user32.MessageBoxW(0, text, title, style)


if  os.path.exists(r"%SystemDrive%\Users\{username}\Documents\QQOutput.bas"):
    Mbox('It exists', 'Please open the csv and then press ok. It will work after 5 seconds', 1)
    time.sleep(5)
    keyboard.press_and_release('alt+f11')
    keyboard.press_and_release('ctrl+m')
    keyboard.write("QQOutput.bas")
    keyboard.press_and_release("enter")
    keyboard.press_and_release("f5")
    keyboard.press_and_release("enter")
else:
    Mbox('Error','QQOutput.bas is not in Documents!. Please put QQOutput.bas in your document folder.', 1)

用户:马可
MessageBox:'请打开csv,然后按ok。它将在5秒后工作'
用户:詹姆斯
MessageBox:'请打开csv,然后按ok。它会在5秒后工作


Tags: and文件csv用户importreleaseifexists
1条回答
网友
1楼 · 发布于 2024-09-29 01:30:25

使用操作系统路径模块。 expanduser('~')返回当前登录用户的主目录的路径。你知道吗

您可以这样在脚本中使用它:

(base) C:\Users\andris>python
Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> doc = os.path.expanduser(r"~\Documents\QQOutput.bas")
>>> doc
'C:\\Users\\andris\\Documents\\QQOutput.bas'
>>> if  os.path.exists(doc):
...   work()

相关问题 更多 >