Python shutil移动保持相同目录结构的文件

Python shutil移动保持相同目录结构的文件,python,Python,我想移动很多文件。这些文件的路径存储在列表中。我想保留整个目录结构,但想将它们移动到另一个文件夹 例如,这些文件是 D:\test\test1\test1.txt D:\test\test1\test2.txt 我想将它们从D:\移动到C:\并保留目录结构。我该怎么做呢 这是我的代码,它不起作用 import os, fnmatch import shutil f=open('test_logs.txt','r') #logs where filenames are stored with

我想移动很多文件。这些文件的路径存储在列表中。我想保留整个目录结构,但想将它们移动到另一个文件夹

例如,这些文件是 D:\test\test1\test1.txt D:\test\test1\test2.txt

我想将它们从D:\移动到C:\并保留目录结构。我该怎么做呢

这是我的代码,它不起作用

import os, fnmatch
import shutil


f=open('test_logs.txt','r') #logs where filenames are stored with filenames as first entry

for line in f:
    filename=line.split()
    output_file="C:" + filename[0].lstrip("D:")
    shutil.move(filename[0],output_file)

我读取文件名很好,可以生成目标文件名,但是当我运行它时,它会给我一个错误,说“没有这样的文件或目录”(并给出输出文件名的路径)

更新:啊,好的,我看到问题了——shutil.move不会复制到不存在的目录。要执行您试图执行的操作,必须首先创建新的目录树。由于使用内置移动功能比滚动您自己的复制和删除过程更安全,因此您可以执行以下操作:

with open('test_logs.txt','r') as f:
    files_to_copy = [line.split()[0] for line in f]
paths_to_copy = set(os.path.split(filename)[0] for filename in files_to_copy)

def ignore_files(path, names, ptc=paths_to_copy):
    return [name for name in names if os.path.join(path, name) not in ptc]

shutil.copytree(src, dst, ignore=ignore_files)

for filename in files_to_copy:
    output_file="C:" + filename.lstrip("D:")
    shutil.move(filename, output_file)
如果不行,请告诉我


原始帖子:如果您只想移动部分文件,最好使用的方法是使用的
忽略
关键字。假设您的文件列表包含完整的路径和目录(即
['D:\test\test1\test1.txt','D:\test\test1\test2.txt','D:\test\test1']
),创建
忽略\u文件
函数并如下使用:

files_to_copy = ['D:\test\test1\test1.txt', 'D:\test\test1\test2.txt', 'D:\test\test1']

def ignore_files(path, names, ftc=files_to_copy):
    return [name for name in names if os.path.join(path, name) not in ftc]

shutil.copytree(src, dst, ignore=ignore_files)
import sys
import os
import shutil

# terminology:
# path = full path to a file, i.e. directory + file name
# directory = directory, possibly starting with a drive
# file name = the last component of the path

sourcedrive = 'D:'
destdrive = 'C:'

log_list_file = open('test_logs.txt', 'r')
for line in log_list_file:
    sourcepath = line.split()[0]  # XXX is this correct?
    if sourcepath.startswith(sourcedrive):
        destpath = sourcepath.replace(sourcedrive, destdrive, 1)
    else:
        print >>sys.stderr, 'Skipping %s: Not on %s' % (sourcepath, sourcedrive)
        continue

    destdir = os.path.dirname(destpath)    

    if not os.path.isdir(destdir):
        try:
            os.makedirs(destdir)
        except (OSError, IOError, Error) as e:
            print >>sys.stderr, 'Error making %s: %s' % (destdir, e)
            continue

    try:
        shutil.move(sourcepath, destpath)
    except (OSError, IOError, Error) as e:
        print >>sys.stderr, 'Error moving %s to %s: %s' % (sourcepath, destpath, e)
然后您只需删除
文件中的文件即可复制

for f in files_to_copy:
    try:
        os.remove(f)
    except OSError:  # can't remove() a directory, so pass
        pass 

我测试了这个--确保您包括了要复制的路径以及
文件中的文件,以便于复制--
--否则,这将删除文件而不复制它们

我想你想要这样的东西:

files_to_copy = ['D:\test\test1\test1.txt', 'D:\test\test1\test2.txt', 'D:\test\test1']

def ignore_files(path, names, ftc=files_to_copy):
    return [name for name in names if os.path.join(path, name) not in ftc]

shutil.copytree(src, dst, ignore=ignore_files)
import sys
import os
import shutil

# terminology:
# path = full path to a file, i.e. directory + file name
# directory = directory, possibly starting with a drive
# file name = the last component of the path

sourcedrive = 'D:'
destdrive = 'C:'

log_list_file = open('test_logs.txt', 'r')
for line in log_list_file:
    sourcepath = line.split()[0]  # XXX is this correct?
    if sourcepath.startswith(sourcedrive):
        destpath = sourcepath.replace(sourcedrive, destdrive, 1)
    else:
        print >>sys.stderr, 'Skipping %s: Not on %s' % (sourcepath, sourcedrive)
        continue

    destdir = os.path.dirname(destpath)    

    if not os.path.isdir(destdir):
        try:
            os.makedirs(destdir)
        except (OSError, IOError, Error) as e:
            print >>sys.stderr, 'Error making %s: %s' % (destdir, e)
            continue

    try:
        shutil.move(sourcepath, destpath)
    except (OSError, IOError, Error) as e:
        print >>sys.stderr, 'Error moving %s to %s: %s' % (sourcepath, destpath, e)

如果源目录为空,是否也要删除它?

是的,我没有移动所有文件,只移动其中一些文件。问题是保持相同的目录结构。未移动的文件会发生什么情况?他们只是呆在原地吗?python2.7:除了(OSError、IOError、shutil.Error)作为e: