How to make python search the entire hard drive
I am making a simple python search program for my computer and I was wondering how I would ask it to scan the entire C drive to look for a file and not a file that is in the same folder as the target file? This is what I have so far.
import os
print('What song would you like to listen to?')
choice = input().title()
os.startfile(choice + '.mp3')
source to share
If you have a search root directory inside, you can use os.walk
. This will result in triplets of directory paths, directories in that directory, and filenames within that directory. For example, if we have this directory structure:
root
βββ dir1
β βββ file1
βββ dir2
β βββ subdir
β βββ file1
β βββ file2
β βββ file3
βββ file1
βββ file2
Then this code:
for path, dirnames, filenames in os.walk('root'):
print((path, dirnames, filenames))
This will print:
('root', ['dir1', 'dir2'], ['file1', 'file2'])
('root/dir1', [], ['file1'])
('root/dir2', ['subdir'], [])
('root/dir2/subdir', [], ['file1', 'file2', 'file3'])
So, if you are looking file3
, you just keep looping until you see file3
in filenames
( operatorin
is appropriate here). Once you see the full path to the file is os.path.join(path, 'file3')
, which you can open with os.startfile
.
source to share
Use the file and directory operations available in the os module . Visit the following part of the Python docs for reference: https://docs.python.org/2/library/os.html#os-file-dir
Please note, you cannot extract metadata from files using these methods, so you need to will need to depend on the player.
Greetings,
- = Cameron
source to share