2013-04-22 100 views
2

使用此代码 我希望它搜索名为sh的所有文件,如sh.c,sh.txt,sh.cpp等。但除非我编写此代码不会搜索lookfor = sh.txtlookfor = sh.pdf而不是lookfor = sh在下面的代码中。 因此,我希望通过编写lookfor = sh它搜索名为sh的所有文件。请帮助。正在搜索文件python

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 

回答

2

替换:

if lookfor in files: 

有了:

for filename in files: 
    if filename.rsplit('.', 1)[0] == lookfor: 

什么filename.rsplit('.', 1)[0]是删除这是一个点(==扩展名)后,找到该文件的最右侧。如果文件中有多个点,我们将其余的文件保存在文件名中。

1

线

if lookfor in files: 

说,如果列表files包含lookfor给出的字符串下面的代码应执行。

但是,您希望测试应该是找到的文件名从给定的字符串开始并继续使用.

此外,你想要确定真实的文件名。

所以,你的代码应该是

import os 
from os.path import join, splitext 
lookfor = "sh" 
found = None 
for root, dirs, files in os.walk('C:\\'): 
    for file in files: # test them one after the other 
     if splitext(filename)[0] == lookfor: 
      found = join(root, file) 
      print "found: %s" % found 
      break 
    if found: break 

这甚至可以改善,因为我不喜欢我怎么休息外for循环的方式。

也许你想拥有它的功能:

def look(lookfor, where): 
    import os 
    from os.path import join, splitext 
    for root, dirs, files in os.walk(where): 
     for file in files: # test them one after the other 
      if splitext(filename)[0] == lookfor: 
       found = join(root, file) 
       return found 

found = look("sh", "C:\\") 
if found is not None: 
    print "found: %s" % found 
+0

当您查找“my”时,这会报告'my.file.pdf'。尽管如此,+1 for'found = join(root,file)' – 2013-04-22 20:08:48

+0

@ThomasOrozco对,因此改变了代码。 – glglgl 2013-04-22 20:10:55

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

您可能需要阅读的fnmatch的doc和太glob的。

3

尝试水珠:

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

或'glob.glob('/ **/sh *')'全部获得它们 – cmd 2013-04-22 20:12:20

1

想必你想SH他们的基本名称搜索文件。 (名称的部分不包括路径和扩展名)您可以使用fnmatch模块的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) 
+0

术语“基本名称”不排除扩展名。请参阅'help(os.path.basename)'。 – glglgl 2013-04-22 20:19:54

+0

Thnx的答案是打印所有文件,但名称即将到来sh。*我想要一个像sh.txt这样的文件的专用名称而不是sh。*。 – 2013-04-22 20:25:39

+1

@glglgl删除扩展名是一个鲜为人知的标准UNIX'basename'实用程序的使用,但它是一样有效和标准的。 [参考这里。](http://pubs.opengroup.org/onlinepubs/009695399/utilities/basename.html)请注意,我没有链接到* python * basename工具,因为我不是在谈论这个。 – kojiro 2013-04-22 22:00:48