从目录列表中复制目录的内容

问题描述 投票:-1回答:1

我想自动将目录内容复制到另一个文件夹。我找到了这篇文章(Copy directory contents into a directory with python),并希望这样做,以便我可以运行for循环。这是我的代码到目前为止,但是我收到一个错误,说无法复制树,因为'X'不是一个目录,其中'X'是我想要复制的目录的文件路径。

我尝试通过简单地从导入的文件列表中复制第一个值来手动运行copy_tree并且它可以工作。我哪里做错了?谢谢。

from distutils.dir_util import copy_tree
import os
location = 'C:/users/trinhsk/desktop/out_space.txt'
with open(location,'r') as f:
    fromDirectory = f.readlines()


for i in fromDirectory:
    bsname = os.path.basename(os.path.dirname(os.path.dirname(i)))
    copy_tree(str(i), "H:/spectraDB_copy/{}/".format(bsname))
python os.path
1个回答
0
投票

readlines()返回的字符串最后有一个EOL字符('\n')。在使用之前尝试剥离线。

for i in fromDirectory:
    i = i.strip()
    bsname = os.path.basename(os.path.dirname(i))
    copy_tree(str(i), "H:/spectraDB_copy/{}/".format(bsname))
© www.soinside.com 2019 - 2024. All rights reserved.