>  기사  >  백엔드 개발  >  Python - 파일 복사

Python - 파일 복사

高洛峰
高洛峰원래의
2016-10-19 15:21:491130검색

최근 휴대폰으로 사진 백업을 하다가 수동으로 하기가 좀 번거로워서 자동으로 할 수 있는 스크립트를 작성해보고 싶었습니다. 일부 사진은 이전에 백업된 적이 있으므로 중복 판단 작업이 필요합니다.

메인 함수는 다음과 같이 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, get 두 개의 파일 목록이 있는데, 무거운 작업을 수행해야 하기 때문에 dst 파일 목록에서 쿼리 작업을 수행해야 합니다. 목록의 쿼리 효율성은 높지 않고, 사전은 해시 테이블이므로 쿼리 효율성이 높기 때문에 대상 파일 목록을 값 없이 키만 있는 사전으로 변환했습니다.

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

그런 다음 소스 파일 목록을 순회합니다. 경로가 폴더인 경우 먼저 폴더가 다음 위치에 있는지 확인합니다. 대상 경로가 없으면 먼저 새 경로를 만듭니다. 그런 다음 이 함수를 재귀적으로 호출합니다. 실제로 존재하지 않는 경우에는 shutdown.copytree() 함수를 호출하는 것이 더 효율적인 방법이지만, 여기서는 복사된 파일의 개수를 계산해야 하므로 이 함수는 호출하지 않는다.

경로가 파일인 경우 먼저 대상 폴더에 파일이 있는지 확인하세요. 존재하지 않는 경우 복사하십시오.

본 스크립트는 주로 모바일 사진첩을 PC와 동기화하기 위해 작성되었기 때문에 파일명만 간략하게 결정합니다. 이름은 다르지만 동일한 파일을 판단하고 싶다면 계속해서 md5 값을 판단하면 되는데, 여기서는 설명하지 않겠습니다.

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
  
# 输入两个文件夹a和b路径,将a中的文件拷进b,并计算拷贝的文件数。重复的不作处理。
# pythontab.com 2013-07-19
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()


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.