1
data_path = "C:\\Users\\Cortex\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\5cfpvg5b.default"

有没有办法动态获取这个文件路径?在这里,5cfpvg5b.default每台计算机都不相同。

4

2 回答 2

4

您可以使用os.getenv()来获取%APPDATA%文件夹的 Windows 位置。Mozilla 文件夹位于此之下。然后您可以使用 Pythonconfigparser读取profiles.ini文件以确定要使用的文件夹:

import configparser
import os

mozilla_profile = os.path.join(os.getenv('APPDATA'), r'Mozilla\Firefox')
mozilla_profile_ini = os.path.join(mozilla_profile, r'profiles.ini')
profile = configparser.ConfigParser()
profile.read(mozilla_profile_ini)
data_path = os.path.normpath(os.path.join(mozilla_profile, profile.get('Profile0', 'Path')))

这将为您提供一条路径,例如:

C:\Users\Cortex\AppData\Roaming\Mozilla\Firefox\Profiles\5cfpvg5b.default

os.path.normpath()用于确保使用反斜杠。

于 2018-05-03T08:34:18.977 回答
1

当您有多个配置文件并切换默认配置时,Martin Evans 的答案不起作用。Profile0 是第一个创建的配置文件,但 bot 是默认配置文件。

所以最后一行应该替换为:

for section in profile.sections():
    if section.startswith("Install"):
        data_path = os.path.normpath(os.path.join(mozilla_profile, profile.get(section, "Default")))
        break
于 2022-02-14T11:57:33.437 回答