-3

I need code that's able to check a folder in the same directory as the python script if it contains either folders or files this code from How to check to see if a folder contains files using python 3 doesn't work

import os

for dirpath, dirnames, files in os.walk('.'):

    if files:

       print dirpath, 'Contains files or folders'

    if not files:

        print dirpath, 'Contains nothing'

The folder I'm checking is DeviceTest

Community
  • 1
  • 1
JJLongOne
  • 7
  • 3

2 Answers2

0

Working

Try this code which uses OSError and aslo os.rmdir never directory which are not empty.So we can use this exception to solve the problem

import os
dir_name = "DeviceTest"
try:
    os.rmdir(dir_name)
except OSError as exception_name:
    if exception_name.errno == errno.ENOTEMPTY:
        print("Directory contains files")
    else:
        print("Directory don't contain files and is empty")

Simple solution

import os
dir_name = "DeviceTest"
if os.listdir(dir_name) == []:
    print("Empty")
Sebastian
  • 5,471
  • 5
  • 35
  • 53
SaiKiran
  • 6,244
  • 11
  • 43
  • 76
0
for path, dirs, files in os.walk(folder): 
        if (files) or (dirs):
            print("NOT EMPTY: " + str(path))
        if (not files) and (not dirs):
            print("EMPTY    : " + str(path))
ADV-IT
  • 756
  • 1
  • 8
  • 10