如何搜索已知扩展名的文件,如.py?

1 投票
4 回答
1804 浏览
提问于 2025-04-15 20:25

怎么查找文件扩展名已知的文件,比如 .py 的文件呢?

fext = raw_input("Put file extension to search: ")
dir = raw_input("Dir to search in: ")

##Search for the file and get the right one's

4 个回答

1

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这种时候,我们可以去一些技术论坛,比如StackOverflow,寻找帮助。在这些论坛上,很多人会分享他们的经验和解决方案,帮助其他人解决类似的问题。

在提问时,最好把问题描述清楚,包括你遇到的错误信息、你使用的编程语言以及相关的代码片段。这样,其他人才能更好地理解你的问题,并给出有效的建议。

有时候,别人可能会给你一些代码示例,或者建议你检查某些特定的地方。这些都是为了帮助你找到问题的根源,进而解决它。

总之,利用这些技术论坛是学习和解决问题的好方法,只要你能清楚地表达你的问题,通常都会有人愿意提供帮助。

import os
root="/home"
ext = raw_input("Put file extension to search: ")
path = raw_input("Dir to search in: ")
for r,d,f in os.walk(path):
    for files in f:
         if files.endswith(ext):
              print "found: ",os.path.join(r,files)
4

我觉得你想做的事情可能是这样的:/dir/to/search/*.extension

这叫做“通配符匹配”,下面是它的用法:

import glob
files = glob.glob('/path/*.extension')

补充一下,这里有相关的文档:http://docs.python.org/library/glob.html

0

非递归:

for x in os.listdir(dir):
    if x.endswith(fext):
        filename = os.path.join(dir, x)
        # do your stuff here

撰写回答