如何使用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.

这是最接近的脚本:

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.

这适用于 Python 3.4,如果这很重要的话.

This is for Python 3.4, if that matters.

感谢您给我的任何帮助.

Thanks for any help you can give me.

'files' 已经告诉你目录中的内容.只需检查一下:

'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')