线
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