安全复制文件python程序-代码有什么问题

时间:2019-02-12 09:20:59

标签: python file copy shutil

我正在尝试将文件从一个目标复制到另一个目标,并且我遵循此程序,但我不知道我做错了什么,但是文件未复制到目标文件夹。 https://gist.github.com/alexwlchan/c2adbb8ee782f460e5ec

我对编程了解不多,我只是按照教程学习。

我在这段代码中添加了其他内容

src = ("F:\\Work\\")
dst = ("F:\\ws\\")

所以如果我错了,请纠正我。

谢谢!

import filecmp
import os
import shutil

src = ("F:\\Work\\")
dst = ("F:\\ws\\")

def _increment_filename(filename, marker='-'):
    basename, fileext = os.path.splitext(filename)
    if marker not in basename:
        base = basename
        value = 0
    else:
        base, counter = basename.rsplit(marker, 1)
        try:
            value = int(counter)
        except ValueError:
            base = basename
            value = 0
    while True:
        if value == 0:
            value += 1
            yield filename
        value += 1
        yield '%s%s%d%s' % (base, marker, value, fileext)

def copyfile(src, dst):
    if not os.path.exists(src):
        raise ValueError('Source file does not exist: {}'.format(src))

    if not os.path.exists(os.path.dirname(dst)):
        os.makedirs(os.path.dirname(dst))

    while True:

        dst_gen = _increment_filename(dst)
        dst = next(dst_gen)

        if os.path.exists(dst):

            if filecmp.cmp(src, dst):
                return dst
            else:

                try:
                    src_fd = os.open(src, os.O_RDONLY)
                    dst_fd = os.open(dst, os.O_WRONLY|os.O_EXCL|os.O_CREAT|os.O_EXLOCK)

                # Read 100 bytes at a time, and copy them from src to dst
                    while True:
                        data = os.read(src_fd, 100)
                        os.write(dst_fd, data)

                    # When there are no more bytes to read from the source
                    # file, 'data' will be an empty string
                        if not data:
                            break

                # If we get to this point, then the write has succeeded
                    return dst

                except OSError as e:
                    if e.errno != 17 or e.strerror != 'File exists':
                        raise
                    else:
                        print('Race condition: %s just popped into existence' % dst)

                finally:
                    os.close(src_fd)
                    os.close(dst_fd)

        # Copying to this destination path has been unsuccessful, so increment
        # the path and try again
            dst = next(dst_gen)

def move(src, dst):
    dst = copyfile(src, dst)
    os.remove(src)
    return dst

程序没有错误,程序可以正常运行,但目标文件夹为空白。

预期结果应该是文件复制到目标文件夹,并且根据程序低于预期结果

如果文件在dst已经存在,则不会被覆盖,但是:

 * If it is the same as the source file, do nothing
 * If it is different to the source file, pick a new name for the copy that
   is distinct and unused, then copy the file there.

1 个答案:

答案 0 :(得分:1)

对不起,但是该代码看上去实在太复杂了。这几乎在所有情况下都适用。如果 dst 已经存在,它将在目录名中添加下划线(_),直到找到未使用的目录为止:

import os
import shutil
import filecmp

src = ("D:\\Documents\\oof")
dst = ("D:\\oof")
validextensions = ["jpeg", "txt", "pdf", "pptx"]


def copydir(src, dst):
    if not os.path.isdir(src):
        print("Source directory doesn't exist.")
        return None
    if not os.path.exists(dst):
        os.mkdir(dst)
    elif not os.path.isdir(dst):
        while not os.path.isdir(dst):
            dst += "_"
        os.mkdir(dst)

    for file in os.listdir(src):
        frompath = os.path.join(src, file)
        topath = os.path.join(dst, file)
        if os.path.isfile(frompath):
            complete = False
            if not any([file[-1 * len(ext):] == ext for ext in validextensions]):
                complete = True
            while not complete:
                if os.path.isfile(topath):
                    if filecmp.cmp(frompath, topath):
                        complete = True
                    else:
                        topath = topath[:topath.index(".")] + "_" + topath[topath.index("."):]
                else:
                    shutil.copyfile(frompath, topath)
                    complete = True
        elif os.path.isdir(frompath):
            copydir(frompath, topath)


copydir(src, dst)

我很喜欢随着OP列出他们想要的更多功能 facepalm

,这变得越来越复杂