我在一個文件夾中有700個文件。我需要找到具有「h10v03」作爲名稱一部分的文件,並使用python將它們複製到不同的文件夾。使用部分名稱在文件夾中搜索文件並使用Python保存/複製到不同的文件夾
繼承人的文件之一的例子:MOD10A1.A2000121.h10v03.005.2007172062725.hdf
我感謝所有幫助。
我在一個文件夾中有700個文件。我需要找到具有「h10v03」作爲名稱一部分的文件,並使用python將它們複製到不同的文件夾。使用部分名稱在文件夾中搜索文件並使用Python保存/複製到不同的文件夾
繼承人的文件之一的例子:MOD10A1.A2000121.h10v03.005.2007172062725.hdf
我感謝所有幫助。
它需要是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查找該文件夾中的所有項目。然後,您可以使用字符串的count()
方法來確定它是否包含您的字符串。然後你可以使用shutil複製文件。
像這樣的東西會做的伎倆。
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)
沒有工作。唯一的想法是我改變了source_dir和tartget_dir。我在這裏錯過的東西? – dchaboya
是的,它需要在Python中,因爲這只是一個較大腳本的一小部分。如果你有時間發佈,一些示例代碼會很棒。我應該提到,我對python相當陌生。 – dchaboya
這裏你去:) - f中的searchstring是區分大小寫的,如果你需要更復雜的匹配,你可以使用正則表達式或globbing模塊。 – sleeplessnerd
是的!謝謝您的幫助。此外,感謝大家的意見。週五愉快。 – dchaboya