search
HomeBackend DevelopmentPython TutorialPython删除空文件和空文件夹的方法

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

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

What is the purpose of using arrays when lists exist in Python?What is the purpose of using arrays when lists exist in Python?May 01, 2025 am 12:04 AM

ChoosearraysoverlistsinPythonforbetterperformanceandmemoryefficiencyinspecificscenarios.1)Largenumericaldatasets:Arraysreducememoryusage.2)Performance-criticaloperations:Arraysofferspeedboostsfortaskslikeappendingorsearching.3)Typesafety:Arraysenforc

Explain how to iterate through the elements of a list and an array.Explain how to iterate through the elements of a list and an array.May 01, 2025 am 12:01 AM

In Python, you can use for loops, enumerate and list comprehensions to traverse lists; in Java, you can use traditional for loops and enhanced for loops to traverse arrays. 1. Python list traversal methods include: for loop, enumerate and list comprehension. 2. Java array traversal methods include: traditional for loop and enhanced for loop.

What is Python Switch Statement?What is Python Switch Statement?Apr 30, 2025 pm 02:08 PM

The article discusses Python's new "match" statement introduced in version 3.10, which serves as an equivalent to switch statements in other languages. It enhances code readability and offers performance benefits over traditional if-elif-el

What are Exception Groups in Python?What are Exception Groups in Python?Apr 30, 2025 pm 02:07 PM

Exception Groups in Python 3.11 allow handling multiple exceptions simultaneously, improving error management in concurrent scenarios and complex operations.

What are Function Annotations in Python?What are Function Annotations in Python?Apr 30, 2025 pm 02:06 PM

Function annotations in Python add metadata to functions for type checking, documentation, and IDE support. They enhance code readability, maintenance, and are crucial in API development, data science, and library creation.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.