Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check to see if a folder contains files using python 3

I've searched everywhere for this answer but can't find it.

I'm trying to come up with a script that will search for a particular subfolder then check if it contains any files and, if so, write out the path of the folder. I've gotten the subfolder search part figured out, but the checking for files is stumping me.

I have found multiple suggestions for how to check if a folder is empty, and I've tried to modify the scripts to check if the folder is not empty, but I'm not getting the right results.

Here is the script that has come the closest:

for dirpath, dirnames, files in os.walk('.'): if os.listdir(dirpath)==[]:     print(dirpath) 

This will list all subfolders that are empty, but if I try to change it to:

if os.listdir(dirpath)!=[]:     print(dirpath) 

it will list everything--not just those subfolders containing files.

I would really appreciate it if someone could point me in the right direction.

This is for Python 3.4, if that matters.

Thanks for any help you can give me.

like image 948
Heather Avatar asked Sep 04 '14 21:09

Heather


People also ask

How do you check if a folder exists in a directory in Python?

os. path. isdir() method in Python is used to check whether the specified path is an existing directory or not. This method follows a symbolic link, which means if the specified path is a symbolic link pointing to a directory then the method will return True.

How can I tell if a file is a folder or a file?

File. isDirectory() checks whether a file with the specified abstract path name is a directory or not. This method returns true if the file specified by the abstract path name is a directory and false otherwise.


1 Answers

'files' already tells you whats in the directory. Just check it:

for dirpath, dirnames, files in os.walk('.'):     if files:         print(dirpath, 'has files')     if not files:         print(dirpath, 'does not have files') 
like image 114
tdelaney Avatar answered Sep 27 '22 17:09

tdelaney