在我的一個專案中,我遇到了這個挑戰:有一個名為Project的檔案夾,其中有多個影像(比如 100 個影像),每個影像都按順序命名,第一個影像名稱是 imag_0,第二個影像名稱是img_2,....imag_99。現在,根據某些條件,我需要分離出一些影像,例如 img_5、img_10、img_30、img_88、img_61。我的問題是,有沒有辦法過濾掉這些影像并在檔案夾Project中創建一個名為“奇怪的”的檔案夾并存盤那些指定的影像?
就我而言,還有一項額外的幫助。假設我有數百個這樣的Projects檔案夾,依次是Projects_1、Projects_2、Projects_3、.....、Projects_99,每個檔案夾都包含數百張圖片。是否可以分離所有指定的照片并將它們存盤在每個Projects_n檔案夾內的單獨檔案夾中,假設我們必須分離出來并以不同方式存盤的照片對于每個Projects_n檔案夾都是相同的?請幫我解決一下這個。謝謝!
uj5u.com熱心網友回復:
對于第一個問題,您可以查找以下偽代碼(您必須指定目標函式)。相反,對于第二個問題,您應該提供更多詳細資訊;
from glob import glob
import itertools
import shutil
import os
# Creating a funtion to check if filename
# is a target file which has to be moved:
def is_target(filename):
if ... return True
else return False
dirname = "some/path/to/project"
# Creating a list of all files in dir which
# could be moved based on type extension:
types = ('*.png', '*.jpeg')
filepaths = list(itertools.chain(*[glob(os.path.join(dirname, f"*.{t}")) for t in types]))
# Finding the files to move:
filepaths_to_move = []
for filepath in filepaths:
if is_target(os.path.basename(filepath)):
filepaths_to_move.append(filepath)
# Creating the new subfolder:
new_folder_name = "odd_images"
new_dir = os.path.join(dirname, new_folder_name)
if not os.path.exists(new_dir): os.makedirs(new_dir)
# Moving files into subfolder:
for filepath in filepaths_to_move:
basename = os.path.basename(filepath)
shutil.move(source, os.path.join(filepath, os.path.join(dirname, basename)))
uj5u.com熱心網友回復:
這是 logic.make 對您的用例進行必要的改進
project_dir = "project_dir"
move_to_dir = os.path.join(project_dir,"move_to_dir")
files = [os.path.join(project_dir,file) for file in os.listdir(project_dir)]
filenames_to_filter = "test1.txt,test2.txt"
if not os.path.exists(move_to_dir):
os.makedirs(move_to_dir)
for(file in files):
if os.path.basename(file) in filenames_to_filter:
shutil.move(file,move_to_dir)
`
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/511789.html
