本文实例讲述了Python删除空文件和空文件夹的方法。分享给大家供大家参考。具体实现方法如下:
#-*- coding:cp936 -*- """ os.walk() 函数声明:walk(top,topdown=True,onerror=None) 1>参数top表示需要遍历的目录树的路径 2>参数topdown的默认值是"True",表示首先返回目录树下的文件,然后在遍历目录树的子目录.Topdown的值为"False"时, 则表示先遍历目录树的子目录,返回子目录下的文件,最后返回根目录下的文件 3>参数onerror的默认值是"None",表示忽略文件遍历时产生的错误.如果不为空,则提供一个自定义函数提示错误信息后继续 遍历或抛出异常中止遍历 4>该函数返回一个元组,该元组有3个元素,这3个元素分别表示每次遍历的路径名,目录列表和文件列表 在2.5版中新增加了一个叫partition的函数,它可以做什么呢?举一个小例子: >>> 'http://www.donews.net/limodou'.partition('://') ('http', '://', 'www.donews.net/limodou') >>> 'file:/a.html'.partition('://') ('file:/a.html', ", ") 从第一个例子可以看出,它用来根据指定的分隔符将字符串进行分割,如果字符串包含指定的分隔符,则返回一个3元的tuple, 第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。第二个例子说明,如果找不到指定的分隔符, 则返回仍然是一个3元的tuple,第一个为整个字符串,第二和第三个为空串 """ import os, sys def remove_empty_dir(path): print path while(path[-1] == "\\"): path = path[:-1] print path a = {} for root, dirs, files in os.walk(path, False): if len(files) == 0: a[root] = 0 else: for file in files: #对文件列表进行扫描 try: fn = os.path.join(root, file) #将路径名和文件名拼接起来 size = os.path.getsize(fn) #获取文件名大小 if size != 0: b = root while(b != path): a[b] = 1 b = b.rpartition("\\")[0] #保存上一级目录名 a[path] = 1 else: try: os.remove(fn) #删除文件名为空的文件 a[root] = 0 except (WindowsError): b = root while(b != path): a[b] = 1 b = b.rpartition("\\")[0] a[path] = 1 except WindowsError: b = root while(b != path): a[b] = 1 b = b.rpartition("\\")[0] a[path] = 1 if a[root]: break; empty_dirs = [] for i, j in a.iteritems(): if j == 0: print i empty_dirs.insert(0, i) del a empty_dirs.sort(reverse=True) for i in empty_dirs: try: os.rmdir(i) #删除目录 print "%s 删掉了!!" % (i) except (WindowsError): print "%s 删不掉!!" % (i) if __name__ == "__main__": remove_empty_dir('f:\\b')
希望本文所述对大家的Python程序设计有所帮助。

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3汉化版
中文版,非常好用

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Atom编辑器mac版下载
最流行的的开源编辑器