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()

猜你喜欢

转载自blog.csdn.net/bro_two/article/details/81708293