我对在目录中搜索图像有疑问。如果图像存在创建文件,文件的名称应类似于(目录名称)。示例 anka.txt 和文件应位于 sade 目录中。
示例:
--LICA
-Horse
-img1
-img1.jpg
-img2.jpg
-img2
-img2.jpg
-img3
-img3.jpg
如何搜索 horse 目录中的所有图像并将它们输出到具有以下描述的文件中: filename = horse.txt 并且内部的马文件内容如下:
/LICA/Horse/img1/img1.jpg
/LICA/Horse/img1/img2.jpg
/LICA/Horse/img2/img2.jpg
/LICA/Horse/img3/img4.jpg
我的代码如下:
def create_positive_list():
try:
for directory, name, img in os.walk(path):
for x in img:
if x.endswith('.jpg'):
var_name = directory.split('/') # Split
file_create = open(path+var_name[1]+'/'+var_name[1]+'.txt','w+') # Create file with name in directory
#print path+var_name[1]
print >> file_create, os.path.join(directory, x)
except IOError, e:
print "Error msg: %s"%e
create_positive_list()
最佳答案
import os
import fnmatch
path='Your Path'
with open(os.path.join(path,'horse.txt'),'w') as hfile:
for r, d, fs in os.walk(path):
for f in fnmatch.filter(fs, '*.jpg'):
hfile.write(os.path.join(r, f))
hfile.write(os.linesep)
关于Python搜索文件并创建输出,写入内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22983281/