4

I want to do this path ('C:\\Users\\%username%\\AppData') but the percent signs used to determine who the user is, is messing up the whole path. I know that you use double backslashes but what do I do when it comes to percent signs?

Thank you, sincerely a python noob :)

Oscar Diego
  • 43
  • 1
  • 4
  • check [this post](https://stackoverflow.com/questions/10678229/how-can-i-selectively-escape-percent-in-python-strings) about how to escape % – Kevin Fang Nov 02 '18 at 03:45
  • @KevinFang But I do not wish to print % I just need it in my path to define the username of the computer. The percent messes with the backslashes in front of it. – Oscar Diego Nov 02 '18 at 03:55

2 Answers2

3

According to the documentation, I think you want to use the os.path.expandvars routine.

On Windows, %name% expansions are supported in addition to $name and ${name}.

import os
my_path = "C:\\Users\\%username%\\AppData"
expanded_path = os.path.expandvars(my_path)
print("The expanded path is: {}".format(expanded_path))

This example works for me in the Python 3.6 command prompt in Windows 7.

Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74
  • Here maybe I can explain better with some screenshots [link](https://imgur.com/6ZYAEBJ) here is a screenshot, as you can see the percent sign and u are purple which they should not be. Thank you for your patience. Here is the whole code, import subprocess subprocess.call(['C:\\Users\\%username%\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories\\notepad.exe']) – Oscar Diego Nov 02 '18 at 04:11
  • I'm guessing the strange colors you're seeing are (to some degree) an edge case in the syntax highlighting in your code editor. What code editor are you using? I wouldn't worry too much about the colors at the moment. The pertinent question is does the code run and do what you expect? – Jonah Bishop Nov 02 '18 at 04:15
  • @JonahBishop I am using sublime text 3, however it does not work. I don't know maybe \\% has some special meaning, like you cannot type C:\Users, you have to (in my case at least) type C:\\Users, the double backslash, I don't know if percent has a similar function. – Oscar Diego Nov 02 '18 at 11:09
  • I've updated the answer to include a print statement. Copy this code, place it in a script, and run it. The script should print out the appropriate path. – Jonah Bishop Nov 02 '18 at 15:48
  • @JonahBishop Hi, I think I have identified the problem. Python identifies the %u part in %username% as a sort of command or something. – Oscar Diego Nov 02 '18 at 18:10
  • I'm not sure I agree with your assessment, given that the snippet of code I have above runs without problems in Windows 7 on Python 3.6... – Jonah Bishop Nov 02 '18 at 22:17
0

You may want to try using os.system:

e.g.

import os
os.system('PATH')
noname1014
  • 91
  • 1
  • 6