os.listdir(): check for files and folders

Let’s start looking into the os.listdir() function. We will make an utility to check files in our hard drive. Let’s start.

os.listdir() to look for files
import os

'''
Whit this script you can check all the files in
a directory:
- all files
- all files of a type
- all folders
- all folders and files

example:
1. All txt files
listdir(file=1, ftype="txt")

2. All folders
listdir(file=2, ftype="")

3. Folders and files
listdir(file=1, ftype="")
'''


def listdir(file=0, ftype=""):
	''' search in all folder G:'''
	if file == 1: # gets only files
		onlyfiles(ftype)
	elif file == 2: # prints only folders
		onlyfolders()
	else: # gets files and folders
		both()


def onlyfiles(ftype):
	''' prints only files '''
	if ftype != "": #gets only files of a type
		for f in os.listdir('G:'): # look in all G:
			if ftype == f.split(".")[-1]: # get all same type files
				print(os.path.abspath(f))
	else: # gets all files
		print(os.path.abspath(f))


def onlyfolders():
	''' prints only folders '''
	for f in os.listdir("G:"):
		if not os.path.isfile(f):
			print(os.path.abspath(f))		


def both():
	''' prints files and folders '''
	for f in os.listdir("G:"):
		print(os.path.abspath(f))



listdir(file=1, ftype="txt")

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.