使用部分名称搜索文件夹中的文件,并使用Python将其保存/复制到不同的文件夹

时间:2011-12-09 21:42:55

标签: python copy

我在一个文件夹中有700个文件。我需要找到有" h10v03"作为名称的一部分,使用python将它们复制到不同的文件夹。

下面是其中一个文件的示例:MOD10A1.A2000121.h10v03.005.2007172062725.hdf

我感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

这样的事情可以解决问题。

import os
import shutil

source_dir = "/some/directory/path"
target_dir = "/some/other/directory/path"

part = "h10v03"
files = [file for file in os.listdir(source_dir)
            if os.path.isfile(file) and part in file]
for file in files:
    shutil.copy2(os.path.join(source_dir, file), target_dir)

答案 1 :(得分:1)

它需要是python吗? unix shell为你做的很好:

cp ./*h10v03* /other/directory/

在python中我建议你看一下os.listdir()和shutil.copy()

修改 一些未经测试的代码:

import os
import shutil

src_dir = "/some/path/"
target_dir = "/some/other/path/"
searchstring = "h10v03"

for f in os.listdir(src_dir):
   if searchstring in f and os.path.isfile(os.path.join(src_dir, f)):
      shutil.copy2(os.path.join(src_dir, f), target_dir)
      print "COPY", f

使用glob模块(未经测试):

import glob
import os
import shutil

for f in glob.glob("/some/path/*2000*h10v03*"):
   print f
   shutil.copy2(f, os.path.join("/some/target/dir/", os.path.basename(f)))

答案 2 :(得分:0)

首先,使用os.listdir查找该文件夹中的所有项目。然后,您可以使用字符串的count()方法来确定它是否包含您的字符串。然后,您可以使用shutil复制文件。