使用此代码,我希望它搜索所有名为sh的文件,如sh.c、sh.txt、sh.cpp etc.But --除非我在下面的代码中编写了lookfor=sh而不是lookfor=sh,否则不会搜索。因此,我希望通过编写lookfor=sh来搜索所有名为sh.Please帮助的文件。
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发布于 2013-04-22 20:05:54
取代:
if lookfor in files:通过以下方式:
for filename in files:
if filename.rsplit('.', 1)[0] == lookfor:filename.rsplit('.', 1)[0]是删除文件中位于点之后的最右边的部分(==,扩展名)。如果文件中有几个点,我们将其馀的保存在文件名中。
发布于 2013-04-22 20:07:12
线
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发布于 2013-04-22 20:08:07
想必您想要搜索以sh作为basename的文件。(名称中不包括路径和扩展名的部分。)您可以使用来自filter模块的fnmatch函数来完成这一任务。
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)https://stackoverflow.com/questions/16155641
复制相似问题