这是我所拥有的:
glob(os.path.join('src','*.c'))
但是我想搜索src的子文件夹。这样做是可行的:
glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))
但这显然是有限和笨拙的。
这是我所拥有的:
glob(os.path.join('src','*.c'))
但是我想搜索src的子文件夹。这样做是可行的:
glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))
但这显然是有限和笨拙的。
当前回答
import sys, os, glob
dir_list = ["c:\\books\\heap"]
while len(dir_list) > 0:
cur_dir = dir_list[0]
del dir_list[0]
list_of_files = glob.glob(cur_dir+'\\*')
for book in list_of_files:
if os.path.isfile(book):
print(book)
else:
dir_list.append(book)
其他回答
这是Python 2.7上的一个工作代码。作为devops工作的一部分,我被要求编写一个脚本来移动标有live-appName的配置文件。属性到appName.properties。可能还有其他扩展文件,比如live-appName.xml。
下面是一个工作代码,它查找给定目录中的文件(嵌套级别),然后将其重命名(移动)到所需的文件名
def flipProperties(searchDir):
print "Flipping properties to point to live DB"
for root, dirnames, filenames in os.walk(searchDir):
for filename in fnmatch.filter(filenames, 'live-*.*'):
targetFileName = os.path.join(root, filename.split("live-")[1])
print "File "+ os.path.join(root, filename) + "will be moved to " + targetFileName
shutil.move(os.path.join(root, filename), targetFileName)
此函数从主脚本调用
flipProperties(searchDir)
希望这能帮助有类似问题的人。
另一种方法是只使用glob模块。只需给rglob方法添加一个起始基本目录和一个要匹配的模式,它就会返回一个匹配文件名的列表。
import glob
import os
def _getDirs(base):
return [x for x in glob.iglob(os.path.join( base, '*')) if os.path.isdir(x) ]
def rglob(base, pattern):
list = []
list.extend(glob.glob(os.path.join(base,pattern)))
dirs = _getDirs(base)
if len(dirs):
for d in dirs:
list.extend(rglob(os.path.join(base,d), pattern))
return list
根据其他答案,这是我目前的工作实现,检索根目录中的嵌套XML文件:
files = []
for root, dirnames, filenames in os.walk(myDir):
files.extend(glob.glob(root + "/*.xml"))
我真的很喜欢python:)
简化版的Johan Dahlin的回答,没有fnmatch。
import os
matches = []
for root, dirnames, filenames in os.walk('src'):
matches += [os.path.join(root, f) for f in filenames if f[-2:] == '.c']
我修改了这篇文章最上面的答案。最近创建了这个脚本,它将循环遍历给定目录(searchdir)中的所有文件和它下面的子目录…并打印文件名、根目录、修改/创建日期和大小。
希望这能帮助到某人…他们可以遍历目录,得到fileinfo。
import time
import fnmatch
import os
def fileinfo(file):
filename = os.path.basename(file)
rootdir = os.path.dirname(file)
lastmod = time.ctime(os.path.getmtime(file))
creation = time.ctime(os.path.getctime(file))
filesize = os.path.getsize(file)
print "%s**\t%s\t%s\t%s\t%s" % (rootdir, filename, lastmod, creation, filesize)
searchdir = r'D:\Your\Directory\Root'
matches = []
for root, dirnames, filenames in os.walk(searchdir):
## for filename in fnmatch.filter(filenames, '*.c'):
for filename in filenames:
## matches.append(os.path.join(root, filename))
##print matches
fileinfo(os.path.join(root, filename))