Home > Blockchain >  How to insert a variable into a file path?
How to insert a variable into a file path?

Time:04-06

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"

CodePudding user response:

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"

CodePudding user response:

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.

  • Related