在python中复制文件的问题

时间:2014-09-24 13:44:40

标签: python copying

我一直在尝试编写一个程序来从文档/ VisualStudio2008文件夹中获取所有.cpp文件,但是我无法将它们复制到桌面。我希望它将所有.cpp从指定文件夹移动到桌面。我有一个标准化的命名方案,我已经做了我能想到的一切。任何帮助表示赞赏。代码如下,如果您需要更多信息,请询问。

import shutil, os

src = ""
dest = ""
chapter = 0
type = ["StepByStep", "Project", "Activity"]
currentType = 0

chapter = int (input("What chapter files would you like to get?\n>> "))
destFolder = input("What do you want the folder name to be?\n>> ")

dest = "C:/Users/17haydent/desktop/"
src = "C:/Users/17haydent/Documents/Visual Studio 2008/Projects/"
#srcEnd = name/name/name.cpp


def upType():
    global currentType
    if currentType == 0:
        currentType = 1
    elif currentType == 1:
        currentType = 2

dest += destFolder

for a in range(1, 3):
    for b in range(1, 20):
        newSrc = src + type[currentType] + str(chapter) + '_' + str(b) + '/' + type[currentType] + str(chapter) + '_'  + str(b) + '/' + type[currentType] + str(chapter) + '_' + str(b) + ".cpp"
       newDest = dest + '/' + type[currentType] + str(chapter) + '_' + str(b) + ".cpp"
    try:
        assert not os.path.isabs(newSrc)
        dstdir =  os.path.join(newDest, os.path.dirname(newSrc))

        os.makedirs(dstdir) # create all directories, raise an error if it already exists
        shutil.copyfile(newSrc, dstdir)
    except:
        print("Error copying file", newSrc, "to", newDest)
upType()

1 个答案:

答案 0 :(得分:0)

您不希望try:newDest = ...处于同一缩进级别吗?

即:

for b in range(1, 20):
    newSrc = src + type[currentType] + str(chapter) + '_' + str(b) + '/' + type[currentType] + str(chapter) + '_'  + str(b) + '/' + type[currentType] + str(chapter) + '_' + str(b) + ".cpp"
    newDest = dest + '/' + type[currentType] + str(chapter) + '_' + str(b) + ".cpp"
    try:
        assert not os.path.isabs(newSrc)

否则只会复制最后一个文件。