Reputation: 7
I have this code that searches all the files from the given directory, but I want to change it so that it can search a file from the users input? and then ask again if the file is not found? The following code i have is:
import os
import sys
from stat import *
def depthsearch(directory):
for files in os.listdir(directory):
fileItem = os.path.join(directory, files)
fileItemStatInfo = os.stat(fileItem)
if S_ISDIR(fileItemStatInfo.st_mode):
depthsearch(fileItem)
elif S_ISREG(fileItemStatInfo.st_mode):
print("Found File:", fileItem)
depthsearch("C:")
Upvotes: 0
Views: 2226
Reputation: 129537
What about
depthsearch(raw_input()) # or 'input()' for Python 3
To check if a given string represents a valid directory, you can use os.path.isdir()
. So you could wrap your call to depthsearch()
in a while loop that keeps asking the user for input until they provide a valid directory.
Upvotes: 2
Reputation: 29804
You can get input by using:
Python 2.X's raw_input
function:
s = raw_input()
s = input()
Upvotes: 1
Reputation: 264
def depthsearch(directory, fileName):
for files in os.listdir(directory):
fileItem = os.path.join(directory, files)
fileItemStatInfo = os.stat(fileItem)
if S_ISDIR(fileItemStatInfo.st_mode):
depthsearch(fileItem,filename)
elif S_ISREG(fileItemStatInfo.st_mode or (files==filename):
print("Found File:", fileItem)
depthsearch("C:", "python.exe")
This allow you to search a file in a directory. It just test if the name are the same.
Upvotes: 0