将文件夹从 A 移动到 B

Move folder from A to B

我有一个文件夹,里面有一些文件,每天自动创建一次。假设该文件夹名为 "bla20150309"(因此会自动添加时间戳)。

现在我想移动那个文件夹,包括。所有它的内容都在别处。到目前为止我的代码:

import time
import datetime
import shutil

ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d')

def copyDirectory(src, dest):
    try:
        shutil.copytree(src, dest)
    # Directories are the same
    except shutil.Error as e:
        print('Directory not copied. Error: %s' % e)
    # Any error saying that the directory doesn't exist
    except OSError as e:
        print('Directory not copied. Error: %s' % e)

copyDirectory("D:/bla%s","E:/hello%s") % (st, st)

所以我想将驱动器 D 上的文件夹 "bla20150309" 移动到驱动器 E 上的 "hello20150309" (我已经在这里的某个地方读到如果你这样做,你需要 shutil 而不是 os.move不同硬盘之间的操作,E盘新文件夹hello20150309还不存在,需要用copy功能创建。

到目前为止我在执行代码时遇到的错误:

TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'

知道如何解决这个问题吗?

您需要先格式化您的目录名称然后将它们传递给您的函数。你现在拥有的:

copyDirectory("D:/bla%s","E:/hello%s") % (st, st)

不行,你要:

copyDirectory("D:/bla%s" % st, "E:/hello%s" % st)

否则你正试图在 copyDirectory() 函数 return 值 上使用 % 运算符,它恰好是 None 在这种情况下。