首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >搜索文件python

搜索文件python
EN

Stack Overflow用户
提问于 2013-04-22 20:00:09
回答 4查看 750关注 0票数 2

使用此代码,我希望它搜索所有名为sh的文件,如sh.c、sh.txt、sh.cpp etc.But --除非我在下面的代码中编写了lookfor=sh而不是lookfor=sh,否则不会搜索。因此,我希望通过编写lookfor=sh来搜索所有名为sh.Please帮助的文件。

代码语言:javascript
复制
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
EN

回答 4

Stack Overflow用户

发布于 2013-04-22 20:05:54

取代:

代码语言:javascript
复制
if lookfor in files:

通过以下方式:

代码语言:javascript
复制
for filename in files:
    if filename.rsplit('.', 1)[0] == lookfor:

filename.rsplit('.', 1)[0]是删除文件中位于点之后的最右边的部分(==,扩展名)。如果文件中有几个点,我们将其馀的保存在文件名中。

票数 2
EN

Stack Overflow用户

发布于 2013-04-22 20:07:12

线

代码语言:javascript
复制
if lookfor in files:

如果列表files包含lookfor中给定的字符串,则应执行以下代码。

但是,您希望测试应该是找到的文件名以给定的字符串开始,并以.继续。

另外,你想要确定真正的文件名。

所以你的代码应该是

代码语言:javascript
复制
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循环的方式。

也许你想把它当作一种功能:

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2013-04-22 20:08:07

想必您想要搜索以sh作为basename的文件。(名称中不包括路径和扩展名的部分。)您可以使用来自filter模块的fnmatch函数来完成这一任务。

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16155641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档