删除文件 c语言 dir,删除文件夹(包括子文件夹)

注意,os.walk等函数可以处理的是unicode类型的中文路径,即处理中文路径时必须转换成unicode类型供函数使用。代码中直接指定中文路径时,使用s.decode("utf-8")。处理输入中文路径时,用s.decode("gbk").还有就是打印时,要将unicode类型字符串转换成gb2312或gbk编码方式。解码,使用decode和unicode函数都可以。

一、使用os.walk

#! /usr/bin/env python

#coding=utf-8

import os

def Remove_dir(top_dir):

if os.path.exists(top_dir)==False:

print "not exists"

return

if os.path.isdir(top_dir)==False:

print "not a dir"

return

for dir_path,subpaths,files in os.walk(top_dir,False):

for file in files:

file_path=os.path.join(dir_path,file)

print "delete file:"+file_path.encode("gbk")

os.remove(file_path)

print "delete dir:"+dir_path.encode("gbk")

os.rmdir(dir_path)

#调用(用户输入:支持中文路径)

input_path=raw_input("dir:")

top_dir=input_path.decode("gbk")

Remove_dir(top_dir)

#调用(代码中指定中文路径)

path=r"C:\Users\Administrator\Desktop\4 - 副本"

unicode_path=path.decode("utf-8")

Remove_dir(unicode_path)

二、使用os.listdir()的循环调用

#! /usr/bin/env python

#coding=utf-8

import os

import sys

def Remove_dir(top_dir):

if os.path.exists(top_dir)==False:

print "not exist"

return

if os.path.isdir(top_dir)==False:

print "This is not a dir"

print top_dir

return

for item in os.listdir(top_dir):

base_path=os.path.join(top_dir,item)

if os.path.isfile(base_path):

try:

os.remove(base_path)

except:

pass

elif os.path.isdir(top_dir):

Remove_dir(base_path) #递归调用

#最后删除顶级目录

try:

os.rmdir(top_dir)

except:

pass

#函数调用

dir="C:\\Users\\Administrator\\Desktop\\新建文件夹 (2)"

unicode_dir=unicode(dir,'utf8')

Remove_dir(unicode_dir)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的示例,每隔一段时间删除指定目录中的所有文件。 ```c #include <stdio.h> #include <stdlib.h> #include <dirent.h> #include <unistd.h> #include <string.h> #include <time.h> #define TIME_INTERVAL 60 // 每60秒删除一次文件 #define DIR_PATH "/tmp/" // 文件夹路径 void delete_files() { DIR *dir; struct dirent *entry; dir = opendir(DIR_PATH); if (dir == NULL) { perror("opendir"); exit(EXIT_FAILURE); } while ((entry = readdir(dir)) != NULL) { if (entry->d_type == DT_REG) { // 如果是文件 char path[1024]; sprintf(path, "%s%s", DIR_PATH, entry->d_name); // 构造文件路径 if (remove(path) == -1) { // 删除文件 perror("remove"); } } } closedir(dir); } int main() { while (1) { time_t current_time = time(NULL); delete_files(); sleep(TIME_INTERVAL - current_time % TIME_INTERVAL); } return 0; } ``` 说明: - `opendir`:打开指定路径下的文件夹。 - `readdir`:读取文件夹中的所有文件文件夹。 - `d_type`:目录项类型,`DT_REG`表示是文件。 - `remove`:删除指定文件。 - `time`:获取当前时间。 - `sleep`:暂停程序执行一段时间。计算出下一次定时删除的时间,然后暂停到那个时间再继续执行。 注意:该程序只删除指定文件夹下的所有文件,但不会删除文件夹。如果要删除文件夹,可以在`delete_files`函数中递归调用该函数。另外,一定要仔细检查文件夹路径,避免删除了不该删除文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值