本文实例讲述了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程序设计有所帮助。

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc

listsandnumpyarraysinpythonhavedifferentmemoryfootprints:listsaremoreflexiblellessmemory-efficient、whileenumpyarraysaraysareoptimizedfornumericaldata.1)listsstorereferencesto objects、with whowedaround64byteson64-bitedatigu

toensurepythonscriptsbehaveCorrectlyAcrossDevelosment、staging、and Production、usetheseStrategies:1)環境variablesforsimplestetings、2)configurationfilesforcomplexsetups、and3)dynamicloadingforadaptability.eachtododododododofersuniquebentandrequiresca

Pythonリストスライスの基本的な構文はリストです[start:stop:step]。 1.STARTは最初の要素インデックス、2。ストップは除外された最初の要素インデックスであり、3.ステップは要素間のステップサイズを決定します。スライスは、データを抽出するためだけでなく、リストを変更および反転させるためにも使用されます。

ListSoutPerformArraysIn:1)ダイナミシジョンアンドフレーケンティオン/削除、2)ストーリングヘテロゼンダタ、および3)メモリ効率の装飾、ButmayhaveslightPerformancostsinceNASOPERATIONS。

toconvertapythonarraytoalist、usetheList()constructororageneratorexpression.1)importhearraymoduleandcreateanarray.2)useList(arr)または[xforxinarr] toconvertoalistは、largedatatessを変えることを伴うものです。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

メモ帳++7.3.1
使いやすく無料のコードエディター

ホットトピック









