CURVX
CURVX

Reputation: 61

Find a file 1 folder level down

I am trying to get full_path of places.sqlite file present in '%APPDATA%\Mozilla\Firefox\Profiles\<random_folder>\places.sqlite' using Python OS module. The issue as you can see that <random_folder> has a random name and there could be multiple folders inside the Profiles folder.

How do I navigate/find the path to the places.sqlite file?

Upvotes: 0

Views: 433

Answers (4)

Aniket Kulkarni
Aniket Kulkarni

Reputation: 471

A glob might be simpler as in this case one expects the file to be there in level below the Profiles folder or not there at all.


import os
import pathlib

profiles = pathlib.Path(os.environ["APPDATA"]) / "Mozilla" / "Firefox" / "Profiles"
# rglob will recursively search as well
if places := list(profiles.rglob("places.sqlite")):
    print(places[0]) # will print the sqllite file path
    with places[0].open() as f:
        # ....

Upvotes: 0

anik jha
anik jha

Reputation: 219

You would ideally want to go through each folder to search for this file. In terminal 'locate file_name' command would do this for you. In python file you can use the following command:

import os


db_path = os.path.join(os.getenv('APPDATA'), r'Mozilla\Firefox\Profiles')


def find_file(file_name, path):
    for root_folder, directory, file_names in os.walk(path):
        if file_name in file_names:
            return os.path.join(root_folder, file_name)


print(find_file('places.sqlite', db_path))

Upvotes: 2

wuerfelfreak
wuerfelfreak

Reputation: 2439

os.walk gives a list of all files in a path recusivly. Use it to search for 'places.sqlite' as follows.

path = ""
for root, dirs, files in os.walk("%APPDATA%\\Mozilla\\Firefox\\Profiles\\"):
    if "places.sqlite" in files:
        path = os.path.join(root, 'places.sqlite')
        break

Upvotes: 2

TheBigW
TheBigW

Reputation: 64

Use the os module to list out all directories in %APPDATA%\Mozilla\Firefox\Profiles\

loop over the directories until you find places.sqlite file (also using os module)

Upvotes: 0

Related Questions