Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/25675352/how-to-check-to-see-if-a-folder-contains-files-using-python-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

'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, 'is empty')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...