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.

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

Thanks for any help you can give me.

感谢你给与我的帮助。

4 个解决方案

#1


20

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

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

for dirpath, dirnames, files in os.walk('.'):
    if files:
        print(dirpath, 'has files')
    if not files:
        print(dirpath, 'is empty')

更多相关文章

  1. 运维利器:钉钉机器人脚本告警(Linux Python 篇)
  2. 从bash脚本传递参数到python解释器
  3. 使用python api递归计算每个Dropbox文件夹大小
  4. Python脚本如何获取当前环节和用户等信息
  5. python mysql 导出到mongodb脚本
  6. 脚本结束后如何运行进程并退出?
  7. 如何获得正在运行的Python脚本的路径?(复制)
  8. Shell脚本更改带变量的目录
  9. CentOS7.2 通过nfs设置共享文件夹

随机推荐

  1. 【MNN学习五】在Android上部署MobileNetS
  2. Android: Attaching Sources to Librarie
  3. Android(安卓)手势检测及通过手势实现翻
  4. [zz http://www.cnblogs.com/oldfeel/arc
  5. Android中RelativeLayout相关属性
  6. Android 错误 'roundIcon' in package 'a
  7. Android编译系统
  8. 扫描二维码自动识别手机系统(Android/IOS)
  9. Android Studio使用问题解决
  10. Android 资源文件中的符号含义与说明