Reputation: 19406
I am coding a search program in python which take the folder for searching for the file as a system argument(sys.argv). It then asks for name of the file to find.
What is the problem
1. How do I know which files or folders are there in the folder? Is there any module or function for that?
Upvotes: 0
Views: 1287
Reputation: 448
This lists all the files in the specified path:
import os
#Change the value of path to a path.
path = "D:\\Pythonic\\"
stuff_in_path = os.listdir(path)
for x in stuff_in_path:
print x
Upvotes: 0
Reputation: 12755
You can use the stuff from os
and os.path
.
import os
path = "xyz"
files = [x for x in os.listdir(path) if os.path.isfile(os.path.join(path,x))]
directories = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path,x))]
This is a rather elegant solution, though this iterates over all entries of os.listdir twice.
Upvotes: 0
Reputation: 35950
Try this:
import os
for item in os.listdir(path):
if not os.path.isfile(os.path.join(path, item)):
print "Folder"
else:
print "File"
Upvotes: 2