python复制文件代码实现
主要功能在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()

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

파이썬에서 문자열을 통해 객체를 동적으로 생성하고 메소드를 호출하는 방법은 무엇입니까? 특히 구성 또는 실행 해야하는 경우 일반적인 프로그래밍 요구 사항입니다.

Uvicorn은 HTTP 요청을 어떻게 지속적으로 듣습니까? Uvicorn은 ASGI를 기반으로 한 가벼운 웹 서버입니다. 핵심 기능 중 하나는 HTTP 요청을 듣고 진행하는 것입니다 ...

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

이 기사는 Numpy, Pandas, Matplotlib, Scikit-Learn, Tensorflow, Django, Flask 및 요청과 같은 인기있는 Python 라이브러리에 대해 설명하고 과학 컴퓨팅, 데이터 분석, 시각화, 기계 학습, 웹 개발 및 H에서의 사용에 대해 자세히 설명합니다.

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...
