简体   繁体   中英

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. 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. 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. 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.

You can use os.path.expanduser to reference user home directory. This will work in Unix and Windows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM