Python 如何在文件路径中使用变量

Python 如何在文件路径中使用变量,python,Python,我想为系统(Windows)上的每个用户事后分析默认的Chrome数据位置。默认_目录的字符串串联起作用。但是我在循环中的两个变量(default_directory和user)不起作用。我正在编写一个使用炭黑API的脚本 for user in users_list: try: default_directory = os.path.normpath('C:\\Users\\' + user + '\\AppData\\Local\\Google\\Ch

我想为系统(Windows)上的每个用户事后分析默认的Chrome数据位置。默认_目录的字符串串联起作用。但是我在循环中的两个变量(default_directory和user)不起作用。我正在编写一个使用炭黑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

提前感谢您的帮助

如果使用原始字符串(如引号前的
r
所示),则不应使用双反斜杠;如果要在字符串中嵌入变量,则应使用f字符串

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

session.create_process(r'C:\\Windows\\cbapi\\hindsight.exe -i "{default_directory}" -o "hindsight_{user}"', wait_timeout=600)
要(如果您使用的是Python 3+):

或者,如果您使用的是Python 2.7,其中不支持f-string,请改用字符串格式化程序:

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

我想您忘记了字符串前面的格式说明符“f”

a = 'some_variable'
out_string = f'this is {a}' # Notice the 'f'
以下各项将起作用:

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