Discuss / Python / 练习第一题,第二题

练习第一题,第二题

Topic source

第一题:简单的处理,判断输入是否是'dir -l'

import os

def Dir_l(command):
    if command == "dir -l":
        curDir = os.path.abspath(".")
        dirlist = os.listdir(curDir)
        for x in dirlist:
            print(x)
    else:
        print("No such command")

command = input("please input command:>>>")
Dir_l(command)

第二题:

def FindFile(filename, value):
    try:
        dirlist = os.listdir(filename)
        for x in dirlist:
            tmp = os.path.join(filename,x)
            if os.path.isdir(tmp):      #tmp必须为绝对路径
                FindFile(tmp, value)
            elif os.path.isfile(tmp):  #tmp必须为绝对路径,不然判断出错
                if value in x:      #if需要路径中包含value则用tmp;否则用x
                    print(tmp)
    except Exception as e:
        print(e)

FindFile('.', 'My')

如果想多次输入,可以改成下面的代码:

def input_command():
    command = input("please input command:>>>\n")
    DIR_L(command)

def DIR_L(command):
    if command == "exit":
        return
    if command == "dir -l":
        curDir = os.path.abspath(".")
        dirlist = os.listdir(curDir)
        for x in dirlist:
            print(x)
        input_command()
    else:
        print("No such command")
        input_command()
input_command()

隨沨漂流

#3 Created at ... [Delete] [Delete and Lock User]

如果有多级目录,这段代码好像并不能查到所有目录下的value文件

houbo111

#4 Created at ... [Delete] [Delete and Lock User]

可以得,有递归调用,绝对路径那边搞了好久才明白


  • 1

Reply