You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python删除文件夹中的文件及基于CSV条件批量删除指定文件

Hey there! Let's tackle your two Python file deletion questions with straightforward, practical solutions. I'll walk you through each scenario step by step.

1. 如何使用Python实现从文件夹中删除文件?

Python offers two reliable approaches to delete files: the classic os module (compatible with all Python versions) and the more modern pathlib module (Python 3.4+). Here's how to use both:

  • 使用os模块
    Use os.remove() (or os.unlink(), which works the same) to delete single files. For bulk deletion of specific file types, iterate through the folder:

    import os
    
    # 删除单个文件
    target_file = "/path/to/your/target/file.jpg"
    try:
        os.remove(target_file)
        print(f"✅ Successfully deleted: {target_file}")
    except FileNotFoundError:
        print(f"❌ Error: The file {target_file} doesn't exist")
    except PermissionError:
        print(f"❌ Error: You don't have permission to delete {target_file}")
    
    # 删除文件夹下所有.png文件
    target_folder = "/path/to/your/folder"
    for filename in os.listdir(target_folder):
        if filename.endswith(".png"):
            file_path = os.path.join(target_folder, filename)
            try:
                os.remove(file_path)
                print(f"Deleted: {file_path}")
            except Exception as e:
                print(f"Failed to delete {file_path}: {str(e)}")
    

    Pro tip: Always add exception handling to avoid crashes from missing files or permission issues.

  • 使用pathlib模块(更简洁的面向对象方式)
    pathlib simplifies file path management with object-oriented syntax. Use Path.unlink() to delete files:

    from pathlib import Path
    
    # 删除单个文件
    target_file = Path("/path/to/your/target/file.jpg")
    try:
        target_file.unlink()
        print(f"✅ Successfully deleted: {target_file}")
    except FileNotFoundError:
        print(f"❌ Error: The file {target_file} doesn't exist")
    except PermissionError:
        print(f"❌ Error: You don't have permission to delete {target_file}")
    
    # 删除文件夹下所有.png文件
    target_folder = Path("/path/to/your/folder")
    for file in target_folder.glob("*.png"):
        try:
            file.unlink()
            print(f"Deleted: {file}")
        except Exception as e:
            print(f"Failed to delete {file}: {str(e)}")
    

    The glob() method makes pattern matching effortless—this is my go-to for modern Python projects.

2. 如何基于CSV文件中的条件批量删除文件夹内的文件?

For your specific case (deleting files where both length and width are less than 50), we'll combine pandas for CSV processing with file deletion logic. Here's a robust, ready-to-use solution:

import pandas as pd
from pathlib import Path

# 读取CSV文件(确保列名和你的实际文件对应!)
df = pd.read_csv('records.csv')

# 筛选符合条件的文件:长度和宽度均小于50
# 替换'长度'/'宽度'为你CSV中实际的列名,比如'length'/'width'
filtered_files = df[(df['长度'] < 50) & (df['宽度'] < 50)]

# 遍历筛选后的文件路径并执行删除
for _, row in filtered_files.iterrows():
    # 替换'文件路径'为CSV中存储文件路径的列名,比如'file_path'
    file_path = Path(row['文件路径'])
    
    # 先确认路径是有效文件,避免误删文件夹或处理不存在的路径
    if file_path.is_file():
        try:
            file_path.unlink()
            print(f"✅ Deleted: {file_path}")
        except PermissionError:
            print(f"❌ Permission denied: Can't delete {file_path}")
        except Exception as e:
            print(f"❌ Error deleting {file_path}: {str(e)}")
    else:
        print(f"⚠️ Skipping: {file_path} is not a valid file or doesn't exist")

Important Reminders:

  • Double-check your CSV column names! Mismatched names (e.g., using length instead of 长度 if your CSV uses Chinese headers) will cause errors.
  • The is_file() check is critical: it prevents accidental folder deletion and skips invalid paths in your CSV.
  • Exception handling ensures the script keeps running even if some files can't be deleted (e.g., due to locked files or missing permissions).

内容的提问来源于stack exchange,提问作者Sohrab Eskandari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 19:54:07