线
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