線
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
當您查找「my」時,這會報告'my.file.pdf'。儘管如此,+1 for'found = join(root,file)' – 2013-04-22 20:08:48
@ThomasOrozco對,因此改變了代碼。 – glglgl 2013-04-22 20:10:55