0

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?

pradyunsg
  • 18,287
  • 11
  • 43
  • 96

3 Answers3

2

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"
ATOzTOA
  • 34,814
  • 22
  • 96
  • 117
0

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.

Thorsten Kranz
  • 12,492
  • 2
  • 39
  • 56
0

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
HelloUni
  • 448
  • 2
  • 5
  • 10