Discuss / Python / 比较简单易懂的2题答案,程序可以运行,但有点小疑惑

比较简单易懂的2题答案,程序可以运行,但有点小疑惑

Topic source

析瓜米米

#1 Created at ... [Delete] [Delete and Lock User]
在此插入代码
#-*— coding:utf-8 -*-
import os
def searching(file_name,path='.'):
    list_file=[]
    list_dir=[]
    f=os.listdir(path)
    for x in f:
        if os.path.isfile(x):
            list_file.append(x)
        else:
            list_dir.append(x)
    print(list_file)
    print(list_dir)
    for k in list_dir:
        m=os.listdir(os.path.join(path,k))
    if file_name in list_file:
        print("在该目录下找到了该文件")
        #print("文件目录是:",os.path.join(path,file_name)
        print(os.path.join(path,file_name))
    elif file_name in m:
            print("在该目录下子目录找到了该文件")
            print("文件目录是:",os.path.join((path,k),file_name))
    else:
        print('对不起,没有要找的文件')

searching('test.py')

参考了@科大骄傲的男神@的答案,他的原程序如下

在此插入代码

import os def S(file_name,path='.'): f=os.listdir(path) list_file=[] #当前目录下的文件 list_dir=[] #当前目录下的目录 for x in f: if os.path.isfile(x): list_file.append(x) else: list_dir.append(x) print(list_file) print(list_dir) if file_name in list_file: print('找到了!') print(os.path.join(path,file_name)) elif: for k in list_dir: m=os.list(os.path.join(path,k)) if file_name in m: print('找到了!') print(os.path.join(os.path.join(path,k),file_name) else: print('对不起,没有找到相关文件!')

使用这个程序时,elif后老是报错,把下面这句放在了前面,程序就可以运行,但不知道为什么?求指点 ```

elif:
    for k in list_dir:
        m=os.list(os.path.join(path,k))       

  • 1

Reply