使用shutil编写Python脚本以移动目录/文件,同时忽略某些目录/文件?

3

我希望构建一个Python脚本,该脚本可以根据一个列表将文件/目录从一个目录移动到另一个目录。

以下是我已经拥有的内容:

import os, shutil

// Read in origin & destination from secrets.py Readlines() stores each line followed by a '/n' in a list

    f = open('secrets.py', 'r')
    paths = f.readlines()

// Strip out those /n

    srcPath = paths[0].rstrip('\n')
    destPath = paths[1].rstrip('\n')

// Close stream

    f.close()

// Empty destPath

    for root, dirs, files in os.walk(destPath, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))

// Copy & move files into destination path

    for srcDir, dirs, files in os.walk(srcPath):
        destDir = srcDir.replace(srcPath, destPath)
        if not os.path.exists(destDir):
            os.mkdir(destDir)
        for file in files:
            srcFile = os.path.join(srcDir, file)
            destFile = os.path.join(destDir, file)
            if os.path.exists(destFile):
                os.remove(destFile)
            shutil.copy(srcFile, destDir)

secrets.py文件包含了src/dest路径。

目前,这将传输所有文件/目录。我想读入另一个文件,允许您指定要传输的文件(而不是制作“忽略”列表)。


你考虑过使用 tarrsync 来完成这个任务吗?它们允许你指定包含或排除文件的文件列表。 - Pedro Romano
1个回答

1
你应该阅读文件列表。
 f = open('secrets.py', 'r')
 paths = f.readlines()

 f_list = open("filelist.txt", "r")
 file_list = map(lambda x: x.rstrip('\n'), f_list.readlines())

 ....
 ....

在复制前请检查

    for file in files: 
       if file in file_list# <--- this is the condition you need to add to your code
          srcFile = os.path.join(srcDir, file)
       ....

如果您的文件列表包含要复制的文件名模式,请尝试使用Python的“re”模块来匹配您的文件名。

太好了,这对于我根目录中的文件完美运作,我如何选择要传输的目录? - Karoh
目前所有目录都已转移。 - Karoh
你能给一个例子吗?因为如果你说你想要复制dir1和file1,但是如果file1存在于dir2中,如果你不复制/创建dir2,那么file1也将不会被复制。 - kalyan
如果你提到要复制一个目录,那么它的所有子目录和文件也应该被复制吗?如果你说要复制一个文件,那么它的所有父文件夹也会被复制吗? - kalyan
如果您提到要复制一个目录,则应该复制其所有子目录及其内容。如果您提到一个文件,只有当它在src目录中时才应该被复制。 - Karoh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接