最近想整理一下工作文件,但是之前寫的用例和腳本放的位置比較雜,如果一個個找太麻煩了,所以寫個腳本來處理,把它們都弄到一個文件里去
本文介紹一下利用python批量把一個文件夾(及其子文件夾)下面的特定類型的文件移動到另一個文件夾下
通過python操作系統目錄及其文件,需要用到os包,本次具體用到如下方法
os.walk(), 這個方法可以遍歷一個文件夾及其子文件(子子文件夾等)
os.rename(),這個方法用於命名文件或目錄(因為是操作一個文件的絕對路徑,所以其實相當於對文件進行剪切操作)
另外也可以借助 shutil庫對文件進行移動或復制操作
下面是示例代碼
def run_main(source_dir, target_dir): num = 0 for root, dirs, files in os.walk(source_dir, topdown=False): # root 表示當前正在訪問的文件夾路徑 # dirs 表示該文件夾下的子目錄名list # files 表示該文件夾下的文件list for name in files: # print(os.path.join(root, name)) # print(type(os.path.join(root, name))) file = os.path.join(root, name) # 拼接文件的完整路徑(注意我們對一個文件或文件夾操作,一定要使用絕對路徑) print(file) if file.split(".")[-1] in ["xls", "xlsx", "csv"]: # 使用split判斷獲得的文件路徑是不是以csv結尾 # print(file) tar_file = file.split(".")[-2]+str(num)+"."+file.split(".")[-1] # 為了避免有重名文件,給原文件名后加一個遞增序號num形成新的文件名 # print(target_dir+tar_file.split("\\")[-1]) if os.path.isfile(target_dir + tar_file.split("\\")[-1]): # 判斷目標文件夾是否已存在該文件 print("已經存在該文件") else: print("正在移動第{}個文件:{}".format(num+1, tar_file.split("\\")[-1])) os.rename(file, target_dir + tar_file.split("\\")[-1]) num += 1 if __name__ == '__main__': run_main("D:/source/", "D:/target/")
關於如何復制文件,還可以借助shutil,可以參考:https://www.jianshu.com/p/7846b6cbe4c8,內容如下

將文件內容拷貝到另一個文件中 1,import shutil 2,shutil.copyfileobj(open('old.xml','r'), open('new.xml','w')) shutil.copyfile(src, dst) 拷貝文件 1,shutil.copyfile('f1.log','f2.log')#目標文件無需存在 shutil.copymode(src, dst) 僅拷貝權限。內容、組、用戶均不變 1,shutil.copymode('f1.log','f2.log')#目標文件必須存在 shutil.copystat(src, dst) 僅拷貝狀態的信息,包括:mode bits, atime, mtime, flags 1,shutil.copystat('f1.log','f2.log')#目標文件必須存在 shutil.copy(src, dst) 拷貝文件和權限 1,import shutil23shutil.copy('f1.log','f2.log') shutil.copy2(src, dst) 拷貝文件和狀態信息 1,import shutil23shutil.copy2('f1.log','f2.log') shutil.ignore_patterns(*patterns) 基本用不到 shutil.copytree(src, dst, symlinks=False, ignore=None) 遞歸的去拷貝文件夾 1,import shutil 2,shutil.copytree('folder1','folder2', ignore=shutil.ignore_patterns('*.pyc','tmp*')) #目標目錄不能存在,注意對folder2目錄父級目錄要有可寫權限,ignore的意思是排除 shutil.rmtree(path[, ignore_errors[, onerror]]) 遞歸的去刪除文件 1,import shutil 2,shutil.rmtree('folder1') shutil.move(src, dst) 遞歸的去移動文件,它類似mv命令,其實就是重命名。 1,import shutil 2,shutil.move('folder1','folder3') shutil.make_archive(base_name, format,...) 創建壓縮包並返回文件路徑,例如:zip、tar 創建壓縮包並返回文件路徑,例如:zip、tar base_name: 壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑, 如 data_bak =>保存至當前路徑 如:/tmp/data_bak =>保存至/tmp/ format: 壓縮包種類,“zip”, “tar”, “bztar”,“gztar” root_dir: 要壓縮的文件夾路徑(默認當前目錄) owner: 用戶,默認當前用戶 group: 組,默認當前組 logger: 用於記錄日志,通常是logging.Logger對象 #將 /data 下的文件打包放置當前程序目錄 import shutil ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data') #將 /data下的文件打包放置 /tmp/目錄 import shutil ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')
其他傳送門