Python3 os模块

1.使用os.walk遍历文件目录

import os

sPath = "G:\\test"
# os.walk遍历
s = tuple(os.walk(sPath, True, None, False))
print(s)

 2.使用深度遍历方式遍历文件目录


# 深度遍历
def DFS(absPath) :
    if (os.path.isabs(absPath)) :
        
        if (os.path.exists(absPath) == False):
            print("当前路径不存在")
            return
        if (os.path.isfile(absPath)) :
            return
        for v in os.listdir(absPath) :
            subPath = os.path.join(absPath, v)
            DFS(subPath)
            print(subPath)
    else :
        return

3.删除包含“f”的文件夹

def DelDirByDFS(absPath) :
    if (os.path.isfile(absPath)) :
        return
    if (absPath.find("f") != -1) :
        for v in os.listdir(absPath) :
            subPath = os.path.join(absPath, v)
            if (os.path.isfile(subPath)) :
                print("删除文件成功")
                os.remove(subPath)
            elif (os.path.isdir(subPath)) :
                DelDirByDFS(subPath)
        print("删除文件夹成功")
        os.rmdir(absPath)
        return

    for v in os.listdir(absPath):
        subPath = os.path.join(absPath, v)
        if (os.path.isdir(subPath)):
            DelDirByDFS(subPath)

4.删除包含“abcd”的文件

def DelFile(absPath) :
    if (os.path.isfile(absPath)) :
        if (absPath.find("abcd") != -1) :
            print("删除文件成功")
            os.remove(absPath)
        return

    for v in os.listdir(absPath):
        subPath = os.path.join(absPath, v)
        DelFile(subPath)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值