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')

      

+3


source to share


2 answers


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

.

+6


source


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

0


source







All Articles