分享一个删除目录下全部文件的python脚本(所有文件类型都可以)



         今天分享一下实习过程减轻工作中一些下载使用后无用的文件的快速删除的代码!

        先上代码吧!哈哈!

import os
import glob

# Define a function to delete text files, handling null bytes in paths
def delete_csv_files(directory):
    # Ensure the directory name is valid and doesn't contain null bytes
    clean_directory = directory.replace('\0', '')
    
    # Use os.listdir to get all files in the directory
    files = os.listdir(clean_directory)
    
    # Iterate over found files and check for .csv files
    csv_files = []
    for file in files:
        if '\0' in file:
            file = file.replace('\0', '')
        if file.endswith('.csv'):
            csv_files.append(os.path.join(clean_directory, file))
    
    # Iterate over found .csv files and remove them
    for csv_file in csv_files:
        try:
            os.remove(csv_file)
            print(f"Deleted {csv_file}")
        except OSError as e:
            print(f"Error deleting {csv_file}: {e}")

# Assuming the directory is provided here as an example
directory = r"D:\xxx"

# Call the function with the directory
delete_csv_files(directory)
print("执行完成")

 文件类型我们可以更改不一定是csv文件,还可以是txt等等不同类型的文件

只需要修改这个:         

if file.endswith('.csv'):

 如果是txt就修改为将.csv => .txt即可!



感谢各位的观看,创作不易,能不能给哥们来一个点赞呢!!!

好了,今天的分享就这么多了,有什么不清楚或者我写错的地方,请多多指教!

私信,评论我呗!!!!!! 

关注我下一篇不迷路哦!

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值