coder_man
coder_man

Reputation: 29

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"

Upvotes: 2

Views: 203

Answers (2)

Tim Roberts
Tim Roberts

Reputation: 54698

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"

Upvotes: 4

BrokenBenchmark
BrokenBenchmark

Reputation: 19242

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.

Upvotes: 4

Related Questions