Python搜索文件并创建输出,写入内容

标签 python file search

我对在目录中搜索图像有疑问。如果图像存在创建文件,文件的名称应类似于(目录名称)。示例 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()

最佳答案

您可以使用fnmatchos walk :

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/

相关文章:

php - 在php mySQL数据库搜索查询中捕获整个单词而不是部分单词

python - 如何使用按另一列分组的 Pandas Dataframe 获取分组大小的方法?

Python检查目录中具有特定名称的所有文件

c# - 哪个最适合用于从 byte[] 创建文件?

java - 标题中的句点在 SOLR 中不可搜索

javascript - AngularJS 过滤器从前面搜索术语而不是整个属性

python - 使用python拆分大文件

python - 关键字参数和字典解包给出不同的结果

python - 在我的 Django Digital Ocean 服务器上的什么位置设置环境变量?

java - Android:如何在android中下载文件?