搜索文件python

2024-09-25 00:23:04 发布

您现在位置:Python中文网/ 问答频道 /正文

使用此代码 我要它搜索所有名为sh的文件,比如sh.c,什.txt,上海cpp等等,但是除非我编写查找,否则此代码不会搜索=什.txt寻找=上海.pdf而不是下面代码中的lookfor=sh。 因此,我希望通过编写lookfor=sh来搜索所有名为嘘,拜托救命啊。在

import os
from os.path import join
lookfor = "sh"
for root, dirs, files in os.walk('C:\\'):
    if lookfor in files:
          print "found: %s" % join(root, lookfor)
          break

Tags: 文件path代码infromimporttxtpdf
3条回答

假设您想搜索以sh作为其基名的文件。(名称中不包括路径和扩展名的部分)您可以使用filter模块中的filter函数来实现这一点。在

import os
from os.path import join
import fnmatch
lookfor = "sh.*"
for root, dirs, files in os.walk('C:\\'):
    for found in fnmatch.filter(files, lookfor):
        print "found: %s" % join(root, found)

试试地球仪:

import glob
print glob.glob('sh.*') #this will give you all sh.* files in the current dir

替换:

if lookfor in files:

有:

^{pr2}$

什么filename.rsplit('.', 1)[0]是删除文件最右边的一个点(=扩展名)后面的部分。如果文件中有几个点,我们将其余的保留在文件名中。在

相关问题 更多 >