[英]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
我相信你想做類似的事情:/ /dir/to/search/*.extension
/to/ /dir/to/search/*.extension
. /dir/to/search/*.extension
?
這叫做glob,以下是如何使用它:
import glob
files = glob.glob('/path/*.extension')
編輯:這里是文檔: 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)
非遞歸:
for x in os.listdir(dir):
if x.endswith(fext):
filename = os.path.join(dir, x)
# do your stuff here
你可以寫的很簡單:
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.