日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 Python教程 正文

如何在python中用os模塊實現批量移動文件_python

作者:Python熱愛者 ? 更新時間: 2022-07-15 Python教程

本文介紹一下利用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

將文件內容拷貝到另一個文件中

import shutil
shutil.copyfileobj(open('old.xml','r'), open('new.xml','w'))
shutil.copyfile(src, dst)

拷貝文件

shutil.copyfile('f1.log','f2.log')#目標文件無需存在
shutil.copymode(src, dst)

僅拷貝權限。內容、組、用戶均不變

shutil.copymode('f1.log','f2.log')#目標文件必須存在
shutil.copystat(src, dst)

僅拷貝狀態的信息,包括:mode bits, atime, mtime, flags

shutil.copystat('f1.log','f2.log')#目標文件必須存在
shutil.copy(src, dst)

拷貝文件和權限

import shutil23shutil.copy('f1.log','f2.log')
shutil.copy2(src, dst)

拷貝文件和狀態信息

import shutil23shutil.copy2('f1.log','f2.log')
shutil.ignore_patterns(*patterns) #基本用不到
shutil.copytree(src, dst, symlinks=False, ignore=None)

遞歸的去拷貝文件夾

import shutil
shutil.copytree('folder1','folder2', ignore=shutil.ignore_patterns('*.pyc','tmp*'))
#目標目錄不能存在,注意對folder2目錄父級目錄要有可寫權限,ignore的意思是排除
shutil.rmtree(path[, ignore_errors[, onerror]]) 

遞歸的去刪除文件

import shutil
shutil.rmtree('folder1')
shutil.move(src, dst)

遞歸的去移動文件,它類似mv命令,其實就是重命名。

import shutil
shutil.move('folder1','folder3')
shutil.make_archive(base_name, format,...)

創建壓縮包并返回文件路徑,例如:zip、tar

base_name: 壓縮包的文件名,也可以是壓縮包的路徑。只是文件名時,則保存至當前目錄,否則保存至指定路徑,

如:/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')

總結

原文鏈接:https://blog.csdn.net/qdPython/article/details/124866958

欄目分類
最近更新