Python3.6 讀取txt內容建立資料夾;將圖片拷貝至指定資料夾,並刪除圖片
阿新 • • 發佈:2018-11-03
讀取txt內容建立資料夾
# 引入模組 import os #建立資料夾 def mkdir(path): # 去除首位空格 path = path.strip() # 去除尾部 \ 符號 path = path.rstrip("\\") # 判斷路徑是否存在 # 存在 True # 不存在 False isExists = os.path.exists(path) # 判斷結果 if not isExists: # 如果不存在則建立目錄 # 建立目錄操作函式 os.makedirs(path) print(path + ' 建立成功') return True else: # 如果目錄存在則不建立,並提示目錄已存在 print(path + ' 目錄已存在') return False ################################################### f = open("error.txt", "r") lines = f.readlines() # 讀取全部內容 for line in lines: # print(line) #拆分字串 line_array = line.split('\t') first_col=line_array[0] #分割出待建立資料夾名稱 # print(first_col) # 定義要建立的目錄 mkpath=(r"error_Images/%s" %(first_col)) # 呼叫函式,建立資料夾 mkdir(mkpath) print(len(lines))
將圖片拷貝至指定資料夾,並刪除
這裡當然可以直接剪下圖片,但是由於要先複製一下,看看正確性,所以是先複製,確認正確以後再刪除圖片。
# 引入模組 #!/usr/bin/env python # coding: utf-8 import os, sys from PIL import Image f = open("error.txt", "r") lines = f.readlines() # 讀取全部內容 i=0 for line in lines: i+=1 line_array = line.split('\t') #拆分字串 line_array2 = line.split('\\') # 拆分字串 first_col=line_array[0] #分割出待建立資料夾名稱 second_col = line_array[1] #分割出待移動的圖片路徑 second_col = second_col.replace('\\', '/') #轉換字元 moveToPath=(r"error_Images/%s" %(first_col)) # 定義要移動的目標目錄 target_ImageName=line_array2[-2]+'_'+line_array2[-1] #目標影象名稱 moveToPathImage=os.path.join(moveToPath,target_ImageName) #合併字串 moveFromPath=("%s" %(second_col)) # 定義要移動的影象路徑 moveFromPath = moveFromPath.strip() # 去除首位空格 moveToPathImage = moveToPathImage.strip() # 去除首位空格 if(os.path.exists(moveFromPath)): #檔案存在 # 複製圖片到新資料夾 # img = Image.open(str(moveFromPath)) # img.save(moveToPathImage) os.remove(str(moveFromPath)) #刪除圖片 else: print("不存在",moveFromPath) a=0 if(i%100==0): print("當前序號%d"% i) # print("原路徑:",moveFromPath) # print("目標路徑:", moveToPathImage) print(len(lines))