Roman Klym
Roman Klym

Reputation: 167

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!

Upvotes: 0

Views: 1244

Answers (2)

Ali Cirik
Ali Cirik

Reputation: 1572

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

Upvotes: 0

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

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.

Upvotes: 1

Related Questions