Discuss / Python / 大家都没审题,我很欣慰

大家都没审题,我很欣慰

Topic source

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

输出相对路径,‘相对’划重点

然后文件名这里应该指的是主文件名,不包括扩展名的吧。

# -*- coding: utf-8 -*-
#!/usr/bin/python
import os
def main():
    str = input('输入查询字符串:')
    path_name = input('输入查询路径(默认为工作路径):')
    if path_name == '':
        path_name = '.'#给懒癌患者一个交代
    minus = len(path_name)

    def list_file(str,path):
        list_all =os.listdir(path)
        for name_f in list_all:
            path_c = os.path.join(path,name_f) 
            if os.path.isfile(path_c) and str in os.path.splitext(name_f)[0]:
                print(path_c[minus:])#把路径前缀去掉
            elif os.path.isdir(path_c):
                list_file(str,path_c)


    list_file(str,path_name)

if __name__ == '__main__':
    main()

zqdllym

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

ifos.path.isfile(path_c) and str in os.path.splitext(name_f)[0]:

大神,您的这一行怎么理解呢

zqdllym

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

好吧,我想我懂了,我需要研究一下它的用法

zqdllym

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

可是大哥,我还是有一点点不太懂。ifos.path.isfile(path_c) and str in os.path.splitext(name_f)[0***]***:    这个***os.path.splitext(name_f)[0******]*** 不是包含了‘‘’点后缀名’‘’前面所有的路径吗,那么如果前面的路径里面只要出现了指定字段不也算是找到了吗,比如他的上级文件夹里,有一个名字和检索字段重合的文件夹,那么不就多找了,可是您的代码是怎么规避这个问题的呢,什么原理

大致思路和大佬差不多,但是对os.path()模块掌握不全,写不到那么好,看了https://www.runoob.com/python/python-os-path.html才明白是啥意思


  • 1

Reply