[英]How do I reference a directory in Python so it works on multiple computers?
I created a Python script that I want to use on different computers.我创建了一个要在不同计算机上使用的 Python 脚本。 I'm using os and pyautogui modules since for pyautogui I have multiple screenshots stored in the folder where py python script is located, also I have a .txt file from which I grab information relevant to the script and should be different on each of those computers.我正在使用 os 和 pyautogui 模块,因为对于 pyautogui 我有多个屏幕截图存储在 py python 脚本所在的文件夹中,我还有一个 .txt 文件,我从中获取与脚本相关的信息,并且每个文件都应该不同电脑。 This is the reference in the script:这是脚本中的引用:
os.chdir(r'C:\Users\myusername\Desktop\Script')
p.FAILSAFE = False
# extracts login and password from a txt file, for each user
credentials = open("login.txt", "r")
for line in credentials:
pieces = line.split(":")
email = pieces[0]
password = pieces[1]
How do I make it accustom to any computer where the script is located and will it work with pyinstaller after I converted the .py file into .exe.我如何使它适应脚本所在的任何计算机,并且在我将 .py 文件转换为 .exe 后它是否可以与 pyinstaller 一起使用。 Thanks!谢谢!
You can create a directory and point to it, the code will be:您可以创建一个目录并指向它,代码将是:
directory_path = os.path.join(os.environ['USERPROFILE'],'Desktop','Script')
if not os.path.isdir(directory_path): os.mkdir(directory_path)
os.environ['USERPROFILE']
gets the user directory for each user in each machine. os.environ['USERPROFILE']
获取每台机器中每个用户的用户目录。
You can use os.path.expanduser
to reference user home directory.您可以使用os.path.expanduser
来引用用户主目录。 This will work in Unix and Windows.这将适用于 Unix 和 Windows。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.