-2

file searching


how would imake a program that would check if my pc had a file with a certain name no matter what type the file is and then print yes or no. For example i would put in a file name then it would print if i had it or not. ive tried similar things but they didnt work for me.

rocks2260
  • 11
  • 4
  • 2
    Does this answer your question? [Find a file in python](https://stackoverflow.com/questions/1724693/find-a-file-in-python) – KetZoomer Apr 12 '21 at 16:44

2 Answers2

2

You can use the os module for this.

import os

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name) # or you could print 'found' or something

This will find the first match. If it exists, it will return the file path, otherwise it returns None. Note that it is case sensitive.

This was taken from this answer.

Have a nice day
  • 1,007
  • 5
  • 11
0

you can also use Pathlib module. The code written using Pathlib will work on any OS.

#pathlib will work on any OS  (linux,windows,macOS)
from pathlib import Path 

 # define the search Path here  '.' means current working directory. you can specify other path like Path('/User/<user_name>')
search_path = Path('.')
# define the file name to be searched here.
file_name = 'test.txt'
#iteratively search glob() will return generator object. It'll be a lot faster.
for file in search_path.glob('**/*'): 
    if file.name == file_name:
        print(f'file found =  {file.absolute()}') #print the file path if file is found
        break
    
Nk03
  • 14,699
  • 2
  • 8
  • 22