Python 如何打开与子目录中的模式匹配的文件
您好,我在查找和打开子目录中的文件时遇到问题。 我有几个不同的文件,例如:Python 如何打开与子目录中的模式匹配的文件,python,Python,您好,我在查找和打开子目录中的文件时遇到问题。 我有几个不同的文件,例如: mouse_1_animal.txt mouse_2_animal.txt mouse_3_animal.txt 所以我想在工作目录的子目录中找到所有这些文件,打开它们,并对这些行进行处理。这是我的尝试: i=1 for path, subdirs, files in os.walk(root) : for file in files : if file == "mouse_{0}_animal.
mouse_1_animal.txt
mouse_2_animal.txt mouse_3_animal.txt 所以我想在工作目录的子目录中找到所有这些文件,打开它们,并对这些行进行处理。这是我的尝试:
i=1
for path, subdirs, files in os.walk(root) :
for file in files :
if file == "mouse_{0}_animal.txt".format(i) :
#do something
i = i + 1
但是很明显,它没有找到所有的文件,所以我想知道这是否是我用来找到文件的方式是错误的
import fnmatch
import os
src = 'sourceDirPath'
for root, dirnames, filenames in os.walk(src):
for filename in fnmatch.filter(filenames, 'mouse*.txt'):
#do something
i = i + 1
对于较旧的python版本,您可能希望尝试glob而不是fnmatch好的,我已经这样解决了我的问题
file_list = []
for name in glob.glob('./subDir/mouse_*_animal.txt'):
file_list.append(name)
for i in range(len(file_list)+1):
if './subDir/mouse_*_animal.txt'.format(i) in file_list:
#do something
蟒蛇的方式:
import glob
for f in glob.glob('./subDir/mouse_*_animal.txt'):
# do_something
我建议获取与模式匹配的所有文件的列表,然后逐个打开、编辑和关闭它们。如果只有一个子目录,则使用
os.listdir()
可能更容易。请注意files
包含与当前路径相关的文件名,其中os.walk
此时所在的路径;因此,您需要连接目录和文件名(os.path.join()
),以获得完整的路径名。glob.glob()
已返回文件名列表。因此,您应该将glob.glob('./subDir/mouse\u*\ u animal.txt')中的f的代码缩短为::do\u something(f)