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?
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"
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.