【发布时间】:2010-03-14 13:19:10
【问题描述】:
如何搜索具有已知文件扩展名的文件,例如 .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
【问题讨论】:
如何搜索具有已知文件扩展名的文件,例如 .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
【问题讨论】:
我相信你想做类似这样的事情:/dir/to/search/*.extension?
这叫做 glob,下面是如何使用它:
import glob
files = glob.glob('/path/*.extension')
【讨论】:
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)
【讨论】:
非递归:
for x in os.listdir(dir):
if x.endswith(fext):
filename = os.path.join(dir, x)
# do your stuff here
【讨论】:
os.path.join吗?我猜x 本身就是filename。
.py 文件时,它会捕获 .epy 文件。此外,glob.glob 是完成这项工作的正确工具。
.py 文件时,它不会捕获.epy 文件。查找py 文件时会这样做。
你可以这么写:
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)]
【讨论】: