python複製檔案代碼實現

來源:互聯網
上載者:User
主要功能在copyFiles()函數裡實現,如下:

複製代碼 代碼如下:


def copyFiles(src, dst):
srcFiles = os.listdir(src)
dstFiles = dict(map(lambda x:[x, ''], os.listdir(dst)))
filesCopiedNum = 0

# 對源檔案夾中的每個檔案若不存在於目的檔案夾則複製
for file in srcFiles:
src_path = os.path.join(src, file)
dst_path = os.path.join(dst, file)
# 若源路徑為檔案夾,若存在於目標檔案夾,則遞迴調用本函數;否則先建立再遞迴。
if os.path.isdir(src_path):
if not os.path.isdir(dst_path):
os.makedirs(dst_path)
filesCopiedNum += copyFiles(src_path, dst_path)
# 若源路徑為檔案,不重複則複製,否則無操作。
elif os.path.isfile(src_path):
if not dstFiles.has_key(file):
shutil.copyfile(src_path, dst_path)
filesCopiedNum += 1

return filesCopiedNum

這裡我首先使用os.listdir()函數來遍曆源檔案夾src和目標檔案夾dst,得到兩個檔案清單,但由於我需要判重操作,因此需要在dst檔案清單中進行查詢操作。由於列表的查詢效率不高,而字典是一個雜湊表,查詢效率較高,因此我將目標檔案列錶轉換成一個只有鍵沒有值的字典:

複製代碼 代碼如下:


dstFiles = dict(map(lambda x:[x, ''], os.listdir(dst)))

然後我遍曆源檔案清單,若該路徑是一個檔案夾,先判斷該檔案夾在目標路徑中是否存在,若不存在,則先建立一個新路徑。然後遞迴調用本函數。其實不存在的時候更高效的方法是調用shutil.copytree()函數,但由於此處需要計算拷貝的檔案數量,因此就沒有調用該函數。

若該路徑是一個檔案,則首先判斷該檔案在目標檔案夾中是否存在。若不存在,則拷貝。

由於寫這個指令碼主要是為了同步手機相簿到PC,因此只簡單地判斷一下檔案名稱。若要判斷不同名但相同的檔案,則可以繼續判斷一下md5值,這裡就不再贅述。

完整代碼如下:

複製代碼 代碼如下:


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# 輸入兩個檔案夾a和b路徑,將a中的檔案拷進b,並計算拷貝的檔案數。重複的不作處理。

import os
import shutil

def copyFiles(src, dst):
srcFiles = os.listdir(src)
dstFiles = dict(map(lambda x:[x, ''], os.listdir(dst)))
filesCopiedNum = 0

# 對源檔案夾中的每個檔案若不存在於目的檔案夾則複製
for file in srcFiles:
src_path = os.path.join(src, file)
dst_path = os.path.join(dst, file)
# 若源路徑為檔案夾,若存在於目標檔案夾,則遞迴調用本函數;否則先建立再遞迴。
if os.path.isdir(src_path):
if not os.path.isdir(dst_path):
os.makedirs(dst_path)
filesCopiedNum += copyFiles(src_path, dst_path)
# 若源路徑為檔案,不重複則複製,否則無操作。
elif os.path.isfile(src_path):
if not dstFiles.has_key(file):
shutil.copyfile(src_path, dst_path)
filesCopiedNum += 1

return filesCopiedNum

def test():
src_dir = os.path.abspath(raw_input('Please enter the source path: '))
if not os.path.isdir(src_dir):
print 'Error: source folder does not exist!'
return 0

dst_dir = os.path.abspath(raw_input('Please enter the destination path: '))
if os.path.isdir(dst_dir):
num = copyFiles(src_dir, dst_dir)
else:
print 'Destination folder does not exist, a new one will be created.'
os.makedirs(dst_dir)
num = copyFiles(src_dir, dst_dir)

print 'Copy complete:', num, 'files copied.'

if __name__ == '__main__':
test()

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.