2

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"

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The \U in that f-string will cause a syntax error unless the \ is escaped or a raw string is used. A raw f-string rf"..." is likely the best choice
Edited, thank you for pointing that out.
4

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"

1 Comment

"Even better" would use pathlib, IMO

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.