內容涉及:關鍵字定位,列表去重復,路徑組裝,文件夾創建,文件拷貝,字符串分割
list.txt的內容為包含關鍵字的文件路徑,如:關鍵字 ’181‘
org/20190523/1/2019052320196231816923IMG039x030.JPG_n_1_1375_220_1475_320.png
org/20190523/7/2019052320196171812302IMG007x030.JPG_p_7_287_191_387_291.png
... ...
import os
import numpy as np
import re
from shutil import copyfile
def getlist(path,name):
listall = []
for n in open(path):
location = re.search(name, n) #定位關鍵字
bingli_Id = n[location.start():location.start()+7] #找到關鍵字后面7位長度字符
listall.append(bingli_Id) #添加到列表中
return set(listall) #去除重復內容
def mkdir(file1, bingId): #建立文件夾
if not os.path.exists(file1):
os.mkdir(file1) #建立一級目錄
for n in bingId:
path = os.path.join(file1, n)
path_1 = os.path.join(path, str(1)) #組裝三級目錄,此時我知道三級目錄的內容,所以直接設置了常量
path_7 = os.path.join(path, str(7))
if not os.path.exists(path): #建立目錄
os.mkdir(path)
if not os.path.exists(path_1):
os.mkdir(path_1)
if not os.path.exists(path_7):
os.mkdir(path_7)
def copytoflods(path_all_list, name, file1):
for n in open(path_all_list):
location = re.search(name, n)
bingId = n[location.start():location.start()+7]
arr = n.split('_') #以‘_’分割字符串
type_ = arr[2] # 取第3個元素
root = os.path.join(file1, bingId, type_, arr[0][-20:]+ '.png') #組裝文件路徑
copyfile(n[:-1], root) #n[:-1]:便捷地去除換行符號
if __name__ == '__main__':
listall = getlist('./list.txt','181') #第一個參數為需要處理的文件路徑列表, 181為關鍵字
mkdir('dataset', listall)
copytoflods('./list.txt','181', 'dataset') #dataset為一級目錄名
