删除指定目录下指定的文件(非并发)

# -*- coding:gbk -*-
import os  
import string  
def del_files(dir,topdown=True):  
    for root, dirs, files in os.walk(dir, topdown):  
        for name in files:  
            pathname = os.path.splitext(os.path.join(root, name))  
            if (pathname[1] == ".sql" ):
                os.remove(os.path.join(root, name))  
                print(os.path.join(root,name))

dir = os.getcwd()  
print(dir)  
del_files(dir)          #will delete the self .py file after run !!!-_-  
\#os.removedirs(dir)      #delete the empty directory recursively

并发的程序参考:
http://blog.youkuaiyun.com/zistxym/article/details/74938797

在C++11中,删除目录下的文件通常涉及到遍历目录并使用`std::filesystem`库来操作文件系统。如果你想删除所有以特定字符串开头的文件,你可以创建一个函数,如下所示: ```cpp #include <iostream> #include <filesystem> void delete_files_with_prefix(const std::string& directory_path, const std::string& prefix) { for (const auto & entry : std::filesystem::directory_iterator(directory_path)) { if (entry.is_regular_file() && entry.path().filename().starts_with(prefix)) { try { std::cout << "Deleting file: " << entry.path() << std::endl; std::filesystem::remove(entry.path()); } catch (const std::filesystem::filesystem_error &e) { std::cerr << "Failed to delete file: " << e.what() << std::endl; } } } } int main() { std::string dir_to_search = "/path/to/your/directory"; std::string prefix_to_match = "file_"; // 想要删除文件名前缀 delete_files_with_prefix(dir_to_search, prefix_to_match); return 0; } ``` 在这个例子中,`delete_files_with_prefix`函数会查找给定目录`directory_path`下的所有以`prefix`开头的普通文件(不是目录),然后尝试使用`std::filesystem::remove`删除它们。 注意: 1. 一定要谨慎使用这个功能,因为删除操作是不可逆的,并且如果没有处理好异常,可能会导致数据丢失。 2. 使用`try-catch`块是为了捕获可能出现的错误,例如权限不足、路径不存在等。 3. 如果需要批量操作大量文件,可能要考虑使用更高级的文件操作策略,如并发处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值