CJHeiser
Posts: 8
Joined: Tue Jul 09, 2013 2:51 am

Searching for Files in Python

Fri Mar 06, 2015 10:06 pm

Let me explain what I am trying to do here. I am trying to make a program where you type in a file name (a song to be exact .mp3) and it will search for it automaticly, without having to type in the directory. So the user types in their song in the Pi terminal, and the program searches through the directories to see if the song is there or not, and if it is, it stores it in a variable (or something similar).

I have been looking around trying to get this to work and I can't. As of now the farthest I've got is this code here,

Code: Select all

import os
basepath = '/home/pi'

def process_dir(dirpath):
    print dirpath

for root, dirs, files in os.walk(basepath):
    for subdir in dirs:
        dirpath = os.path.join(root,subdir)
        process_dir(dirpath)
However it doesn't let me search for a specific file, it just displays everything in the /home/pi folder.

Thanks for the help everyone! All help is very much appreciated!
Thanks,
Cody
Thanks,
Cody

User avatar
elParaguayo
Posts: 1943
Joined: Wed May 16, 2012 12:46 pm
Location: London, UK

Re: Searching for Files in Python

Sat Mar 07, 2015 1:17 pm

I think you could do something simple like this with your code:

Code: Select all

import os

base = "/home/pi"

target = raw_input("Enter name of file to find: ")

for root, dirs, files in os.walk(base):
  if target in files:
    print "Target found"
    print os.path.join(root, target)
So you just enter the file name that you're looking for and, if it finds it, it prints the path to the file.

There may be better ways of doing this but I've just tweaked your code to help you do what you want.
RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc.

CJHeiser
Posts: 8
Joined: Tue Jul 09, 2013 2:51 am

Re: Searching for Files in Python

Sat Mar 07, 2015 7:08 pm

elParaguayo wrote:I think you could do something simple like this with your code:

Code: Select all

import os

base = "/home/pi"

target = raw_input("Enter name of file to find: ")

for root, dirs, files in os.walk(base):
  if target in files:
    print "Target found"
    print os.path.join(root, target)
So you just enter the file name that you're looking for and, if it finds it, it prints the path to the file.

There may be better ways of doing this but I've just tweaked your code to help you do what you want.
Thank you so much! That was it!
Thanks,
Cody

Return to “Python”