python3資料夾相關操作--建立新資料夾,刪除檔案,移動檔案,獲取指定檔案下的檔案和數量
阿新 • • 發佈:2020-12-19
1. 建立新資料夾
若存在且不為空,刪除舊資料夾,重新建立
# coding=utf-8
import glob
import shutil
import os
def PicPath(path):
if os.path.exists(path):
print(path, " is exists!")
if not os.listdir(path):
print(path, " is empty!")
else:
print (path, " is not empty ")
shutil.rmtree(path, True)
print("old path delete successfully")
os.makedirs(path)
print("new image path is Recreated successfully!")
else:
print(path, " is not exists!")
os. makedirs(path)
print("new image path is created successfully!")
2.獲取指定檔案下的檔案和數量
def image_select(path):
image_file = []
for filename in os.listdir(path):
image_file.append(os.path.join(path, filename))
file_number = len(image_file) # 指定檔案下的檔案個數
return image_file, file_number
3.移動資料夾下的指定型別檔案
def backup(srcfile, dst_dir):
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
print('資料夾建立完成 ' + dst_dir)
src_file_list = glob.glob(srcfile+ '*.*') # glob獲得路徑下所有檔案,可根據需要修改
print (src_file_list)
for srcfile in src_file_list:
shutil.move(srcfile, dst_dir) # 移動檔案
print ("move %s -> %s" % (srcfile, dstpath+'/'+fname))