簡體   English   中英

使用名稱的一部分搜索文件夾中的文件,並使用Python保存/復制到其他文件夾

[英]Search files in folder using part of the name and save/copy to different folder using Python

我在一個文件夾中有700個文件。 我需要查找名稱中包含“ h10v03”的文件,然后使用python將其復制到其他文件夾中。

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

感謝您的幫助。

這樣的事情可以解決問題。

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)

需要是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)))

首先,使用os.listdir在該文件夾中找到所有項目。 然后,您可以使用string的count()方法來確定它是否包含您的字符串。 然后,您可以使用shutil復制文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM