如果它包含文件夹或文件,我需要能够检查与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
答案 0 :(得分:0)
<强>工作强>
尝试使用OSError的代码和aslo os.rmdir从不为空的目录。所以我们可以使用此异常来解决问题
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")
答案 1 :(得分:0)
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))