2013-04-22 99 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