【问题标题】:Check a folder if it contains anything python3检查一个文件夹是否包含任何东西 python3
【发布时间】:2016-06-19 13:37:49
【问题描述】:

我需要能够检查与 python 脚本位于同一目录中的文件夹是否包含文件夹或文件的代码 How to check to see if a folder contains files using python 3 的这段代码不起作用

import os

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

    if files:

       print dirpath, 'Contains files or folders'

    if not files:

        print dirpath, 'Contains nothing'

我正在检查的文件夹是 DeviceTest

【问题讨论】:

    标签: python-3.x directory


    【解决方案1】:

    工作

    试试这段代码,它使用了 OSError 和 aslo os.rmdir never 目录不为空。所以我们可以使用这个异常来解决问题

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

    简单的解决方案

    import os
    dir_name = "DeviceTest"
    if os.listdir(dir_name) == []:
        print("Empty")
    

    【讨论】:

    • 这是检查当前目录还是我必须更改目录才能检查它?
    • 转到根目录,它会检查它是否为空,如果你想检查给定文件夹中的所有文件夹,你可以遍历整个目录
    • 你可以编辑你的代码让它检查当前目录中的DeviceTest
    • DeviceTest到底是什么,是文件名还是子目录?
    • 它是工作目录中的一个目录,我要检查它,如果它包含任何东西,例如文件或文件夹
    【解决方案2】:
    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 2017-06-30
      • 2018-07-17
      • 2012-06-03
      相关资源
      最近更新 更多