[英]how to search for file's has a known file extension like .py?
how to search for file's has a known file extension like .py ?? 如何搜索文件有一个已知的文件扩展名,如.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
I believe you want to do something like similar to this: /dir/to/search/*.extension
? 我相信你想做类似的事情:/ /dir/to/search/*.extension
/to/ /dir/to/search/*.extension
. /dir/to/search/*.extension
?
This is called glob and here is how to use it: 这叫做glob,以下是如何使用它:
import glob
files = glob.glob('/path/*.extension')
Edit: and here is the documentation: http://docs.python.org/library/glob.html 编辑:这里是文档: http : //docs.python.org/library/glob.html
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)
Non-recursive: 非递归:
for x in os.listdir(dir):
if x.endswith(fext):
filename = os.path.join(dir, x)
# do your stuff here
You can write is as simple as: 你可以写的很简单:
import os
ext = raw_input("Put file extension to search: ")
path = raw_input("Dir to search in: ")
matching_files = [os.path.join(path, x) for x in os.listdir(path) if x.endswith(ext)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.