Discuss / Python / 只能匹配全文件名,匹配字符串还需要加入正则表达式吧

只能匹配全文件名,匹配字符串还需要加入正则表达式吧

Topic source

-- coding: utf-8 --

import os

name = input('input name of finding file: ') path = input('input name of finding path: ')

def findfile(name,path='.'): pwd = os.path.abspath(path) for f in os.listdir(pwd): if os.path.isdir(f): findfile(name,f) if os.path.isfile(os.path.join(pwd,f)) and os.path.splitext(f)[0] == name: print('The file in:') print(os.path.join(pwd,f))

findfile(name,path)


不知道为何,第二个法IF如果这么写 if os.path.isfile(f) and os.path.splitext(f)[0] == name:

就不会查找txt格式的文件,只查到了py格式的文件

啊呜说

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

我也有这个问题 只能遍历当层的 ,然后我搜了下别人写的 他们会在前后加上这行代码 os.chdir()这个方法

def scanfir(startdir,path1=[]):

os.chdir(startdir)

for obj in os.listdir(startdir):

path = os.getcwd()+os.sep+obj

if os.path.isdir(obj):

scanfir(path)

os.chdir(os.pardir)

if os.path.isfile(obj):

path1.append(path)

# print(os.chdir(os.pardir))

return path1

t=scanfir('.')

print(len(t))

作者说 函数chdir的作用是切换到指定目录,该参数必须是有效的且有访问权限的相对路径或绝对路径

啊呜说

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

= = 我错了 代码这么大一串


  • 1

Reply