python学习之操作文件和目录

廖雪峰python教程习题:
1.利用os模块编写一个能实现dir -l输出的程序。
2.编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。

#1.利用os模块编写一个能实现dir -l输出的程序。

import os

def dir_l(path = '.'):
    L = os.listdir(os.path.abspath(path))
    for file in L:
        print(file)

#2.编写一个程序,能在当前目录以及当前目录的所有子目录下 查找 文件名包含指定字符串的文件,并打印出相对路径。

def findFile(fileName):

    dirlist = os.walk(os.path.abspath('.'))

    find = list()

    for parent, dir, files in dirlist:
        for file in files:
            if fileName in file:
                xiangDuiPath = parent.replace(os.path.abspath('.'),'.')
                print(os.path.join(xiangDuiPath, file))
                find.append(os.path.join(xiangDuiPath,file))

    if len(find) == 0:
        print('Not found')
        return

    return find

findFile('text.txt')

ps:反复调用

import os

def find():
    findstr = str(input('请输入要查找的文件名(输入“exit”可退出):\n >>>'))
    if findstr == 'exit':
        confirm_1 = input('是否要结束查询(yes / no):\n >>>')
        if confirm_1 == 'yes': 
            return
        else:
            find()
    else:  
        findFile(findstr)


def findFile(findstr):
    dirlist = os.walk(os.path.abspath('.'))
    result = list()

    for root, dirs, files in dirlist:
        for file in files:
            if findstr in file:
                print('包含“%s”的文件路径为:'% findstr ,os.path.join(root, file))
                result.append(os.path.join(root,file))

    if len(result) == 0:
        print('没有查找到包含“%s”的文件'%findstr)
        find()
    else:
        confirm_2 = input('是否要结束查询(yes / no):\n >>>')
        if confirm_2 == 'no':
            find()
        else:
            return
find()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值