本文介绍了如何确定文件夹是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查一个名为foldername的文件夹。是空的。

我用os.listdir(foldername)== []这样做,

但是如果文件夹有很多子文件,它会很慢文件。

有没有有效的方法呢?

谢谢〜

解决方案




首先要做的是测量这个操作的性能

在你的应用程序的上下文中看看它是否真的值得额外

努力。

调整这将取决于平台。在Windows上,您可以使用

ctypes和系统函数FindFirstFile / FindNextFile / FindClose,

一旦看到单个文件就完成。目录始终包含。。和

" .."这些条目应该被忽略。在其他平台上会有类似低级功能的




Neil




首先要做的是在你的应用程序的上下文中测量这个操作的性能,看它是否真的值得额外调整这将取决于平台。在Windows上,您可以使用
ctypes和系统函数FindFirstFile / FindNextFile / FindClose,
一旦看到单个文件就完成。目录始终包含。。和
..这些条目应该被忽略。在其他平台上会有类似的低级功能。

Neil
-






试试:

os.rmdir(路径)

empty = True

除了OSError:

empty = False


应该是高效的。一个目录(请停止称它们为文件夹)

只有在空的时候才能删除。


Reinhold

I want to check if a folder named "foldername" is empty.
I use os.listdir(foldername)==[] to do this,
but it will be very slow if the folder has a lot of sub-files.
Is there any efficient ways to do this?
Thanks~

解决方案



The first thing to do is measure the performance of this operation
in the context of your application to see if it is really worth extra
effort.
Tweaking this will depend on the platform. On Windows you can use
ctypes and the system functions FindFirstFile/FindNextFile/FindClose,
finishing once you see a single file. Directories always contain "." and
".." entries so they should be ignored. On other platforms there will be
similar low level functions.

Neil




The first thing to do is measure the performance of this operation
in the context of your application to see if it is really worth extra
effort.
Tweaking this will depend on the platform. On Windows you can use
ctypes and the system functions FindFirstFile/FindNextFile/FindClose,
finishing once you see a single file. Directories always contain "." and
".." entries so they should be ignored. On other platforms there will be
similar low level functions.

Neil
--
http://mail.python.org/mailman/listinfo/python-list





try:
os.rmdir(path)
empty = True
except OSError:
empty = False

should be efficient. A directory (please stop calling them "folders")
can only be removed if it''s empty.

Reinhold


这篇关于如何确定文件夹是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:43