user3022917
user3022917

Reputation: 611

How to use variables in file path

I would like to analyze the default Chrome data location with Hindsight for every user on the system (Windows). The string concatenation for default_directory works. But my two variables (default_directory and user) in the loop are not working. I'm writing a script for using the Carbon Black API.

for user in users_list:
        try:
            default_directory = os.path.normpath('C:\\Users\\' + user + '\\AppData\\Local\\Google\\Chrome\\User Data\\Default') # String concatenation
            session.create_process(r'C:\\Windows\\cbapi\\hindsight.exe -i "{default_directory}" -o "hindsight_{user}"', wait_timeout=600) 
        except Exception: pass

Thank you in advance for your assistance!

Upvotes: 2

Views: 256

Answers (2)

blhsing
blhsing

Reputation: 106445

You should not use double backslash if you are using a raw string (as denoted by the r before the quote), and you should use an f-string if you are going to embed variables inside the string.

Change:

session.create_process(r'C:\\Windows\\cbapi\\hindsight.exe -i "{default_directory}" -o "hindsight_{user}"', wait_timeout=600)

to (if you're using Python 3+):

session.create_process(fr'C:\Windows\cbapi\hindsight.exe -i "{default_directory}" -o "hindsight_{user}"', wait_timeout=600)

or, if you're using Python 2.7, where f-string is not supported, use the string formatter instead:

session.create_process(r'C:\Windows\cbapi\hindsight.exe -i "{}" -o "hindsight_{}"'.format(default_directory, user), wait_timeout=600)

Upvotes: 2

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

I think you forgot the format specifier 'f' before the string.

a = 'some_variable'
out_string = f'this is {a}' # Notice the 'f'

The below will work:

for user in users_list:
        try:
            default_directory = os.path.normpath('C:\\Users\\' + user + '\\AppData\\Local\\Google\\Chrome\\User Data\\Default') # String concatenation
            session.create_process(fr'C:\\Windows\\cbapi\\hindsight.exe -i "{default_directory}" -o "hindsight_{user}"', wait_timeout=600) 
        except Exception: pass

Upvotes: 0

Related Questions