如何输入作为字符串一部分的变量文件路径 (Python)

How to input a File Path which is a variable as part of a String (Python)

我正在尝试在我的 Chromedriver 的默认下载目录中插入一个字符串变量,如下所示:

path = str(os.getcwd())
pdf_path = str(path + '\pdf')


chrome_options = Options()
chrome_options.add_experimental_option('prefs',  {
    "download.default_directory": '%s',
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "plugins.always_open_pdf_externally": True,
    "profile.default_content_setting_values.automatic_downloads": 1
    }
%(path))

然后我遇到了以下错误:

TypeError: unsupported operand type(s) for %: 'dict' and 'str'

据我所知,这是使用 %s 插入字符串变量时的正确语法。问题看起来很简单,我似乎找不到解决方案,因为经过一些研究后,我没有遇到任何人在 chrome 驱动程序选项中插入 '%s' 的例子。

Python 不允许您以这种方式格式化字典。这是格式化字典的方法。尝试将行更改为:

"download.default_directory": f'{path}'

字典现在应该看起来像这样:

chrome_options = ('prefs',  {
    "download.default_directory": f'{path}',
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "plugins.always_open_pdf_externally": True,
    "profile.default_content_setting_values.automatic_downloads": 1
    })