Matt Dweller
Matt Dweller

Reputation: 39

Using an Environmental Variables In a Variety of Path Types

How would I go about using the same method for using the USERNAME variable in the top portion of code in the bottom code, I just feel like I don't have a grounded knowledge of the syntax with variables in in python yet:

Code:1

msg['Subject'] = os.environ['USERNAME'] #This is the working method i use to call upon    the USER NAME Variable.

Code:2

import os
os.makedirs.environ [("C:\Users\'USERNAME'\AppData\Roaming\Microsoft\Windows\StartMenu\Programs\Data")]

#This is the path type that i don't know how to use the Environmental Variable's With, this would be my best guess at how this would be done.

Default Code with no edits:

import os
os.makedirs("C:\Users\'USERNAME'\AppData\Roaming\Microsoft\Windows\StartMenu\Programs\Data)

Question: So these two method's are working superbly:

import os
os.mkdir(os.path.expandvars("C:\\users\\%username%\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Data"))


import os
username = os.environ['USERNAME']
os.mkdirs("C:\Users\%s\AppData\Roaming\Microsoft\Windows\StartMenu\Programs\Data" %    username)

But i'm Still a little confused on how to use the variable's that require 2 path's like Copy, Here's an Example:

copyfile(src, dst)

Or 

Copy(Src, dst)

P.S. I'm really curious what I should look into to start understanding the structure of scripts/ the rule's of thumb when it comes to the format you write them in.

Upvotes: 1

Views: 640

Answers (2)

Mike Corcoran
Mike Corcoran

Reputation: 14565

You need to expand the environment variables in the string, before you pass it to os.mkdir or os.makedirs. The function you want to use for that is os.path.expandvars. Also, environment variables in windows are delimited with the % character, not the ' character.

So your code should look more like this:

import os
os.mkdir(os.path.expandvars("C:\\users\\%username%\\rest\\of\\path"))

Upvotes: 3

nofinator
nofinator

Reputation: 3023

First try grabbing the username, then making the directory, like so:

import os

username = os.environ['USERNAME']
os.mkdirs("C:\Users\%s\AppData\Roaming\Microsoft\Windows\StartMenu\Programs\Data" % username)

If you're looking to access the user's Start Menu, you may want to try %APPDATA% instead for better portability:

os.path.join(os.environ['APPDATA'], "Microsoft\Windows\StartMenu\Programs\Data")

Upvotes: 2

Related Questions