如何用更Pythonic的方式删除指定列表中的空文件?
更Pythonic的空文件删除写法
嘿,你提到的这个点非常到位——用== 0做布尔判断确实不够符合Python的惯用风格。咱们可以利用Python的“真值测试”特性来优化这段代码,让它更简洁优雅。
直接优化核心判断
在Python里,0、空容器、空字符串等都会被视为“假值”,所以我们可以直接用not来检查文件大小是否为0,替代显式的== 0判断:
import os book_list = ['Automate the Boring Stuff with Python.pdf', 'OReilly.Think.Python.2nd.Edition.2015.12.pdf', 'Apress-Magnus_Lie_Hetland-python_algorithms.pdf', 'Python for Data Analysis - 2012.pdf'] for book in book_list: if not os.path.getsize(book): os.remove(book)
这段代码的逻辑和原来完全一致,但读起来更流畅,也更符合Python倡导的“简洁可读”的风格。
额外的鲁棒性优化(可选)
如果你的book_list里可能包含不存在的文件,直接调用os.path.getsize会抛出FileNotFoundError。我们可以用两种Pythonic的方式处理这种情况:
方式1:先检查文件存在性
import os book_list = ['Automate the Boring Stuff with Python.pdf', 'OReilly.Think.Python.2nd.Edition.2015.12.pdf', 'Apress-Magnus_Lie_Hetland-python_algorithms.pdf', 'Python for Data Analysis - 2012.pdf'] for book in book_list: if os.path.exists(book) and not os.path.getsize(book): os.remove(book)
方式2:用try-except捕获异常(更推荐)
Python里有“请求原谅比请求许可更好”的设计哲学,所以用异常处理来捕获可能的错误会更优雅:
import os book_list = ['Automate the Boring Stuff with Python.pdf', 'OReilly.Think.Python.2nd.Edition.2015.12.pdf', 'Apress-Magnus_Lie_Hetland-python_algorithms.pdf', 'Python for Data Analysis - 2012.pdf'] for book in book_list: try: if not os.path.getsize(book): os.remove(book) except FileNotFoundError: print(f"跳过不存在的文件:{book}")
这样即使列表里有无效的文件名,程序也能继续运行,不会直接崩溃。
内容的提问来源于stack exchange,提问作者user9062604
相关产品推荐
相关产品推荐

