【问题标题】:Python search for file and create output, write contentPython 搜索文件并创建输出,写入内容
【发布时间】:2014-04-10 08:57:16
【问题描述】:

我对通过目录搜索图像有疑问。如果图像存在创建文件,文件应具有类似(目录名称)的名称。示例 anka.txt 和文件应该是 insade dir。

例子:

--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()

【问题讨论】:

  • 您目前所拥有的有什么问题?更具体。

标签: python file search


【解决方案1】:

您可以使用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)

【讨论】:

  • 非常感谢!很好很容易:)
【解决方案2】:

您可以使用glob 来匹配您要查找的模式。

>>> import glob
>>> glob.glob('*.jpg')
['my.jpg']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    相关资源
    最近更新 更多