'How to insert a variable into a file path?
I have the following code:
import os
current_user = os.getlogin()
target_path = r"C:\Users\{I want the current user variable inserted here}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
but it just prints out as
"C:\Users\current_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
Solution 1:[1]
Use a format string, not a raw string:
import os
current_user = os.getlogin()
target_path = rf"C:\Users\{current_user}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
We use rf rather than f here, as we need to prevent \U from being interpreted as a Unicode escape sequence, as Brian points out.
Solution 2:[2]
I believe you want
target_path = rf"C:\Users\{current_user}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
but even better is
target_path = os.environ["APPDATA"]+"\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
