【问题标题】:Copy files along with file paths from a list to a folder or another path将文件连同文件路径从列表复制到文件夹或其他路径
【发布时间】:2020-08-15 16:16:53
【问题描述】:

我有一个包含文件及其路径的列表。我需要将文件及其整个路径复制或移动到另一个目录或文件夹中。

我尝试如下,但路径无法复制路径,只复制文件。

import shutil
list_l1 = ['/home/Test//A/Aa/hello1.c', '/home/Test/C/Aa/hello1.c', '/home/Test/B/Aa/hello1.c']
for source in list_l1:
    shutil.move(source, '/home/Test/sample_try/sample/')

【问题讨论】:

    标签: python copy shutil


    【解决方案1】:

    您可能想使用os.makedirs() 来创建嵌套目录。您可能希望先将list_l1 中的路径分成目录和文件名部分,然后在尝试创建目录之前使用os.path.exists() 检查目录是否存在。

    你可以试试:

    import shutil
    import os
    
    list_l1 = ['/home/Test//A/Aa/hello1.c', '/home/Test/C/Aa/hello1.c', '/home/Test/B/Aa/hello1.c']
    dest = '/home/Test/sample_try/sample'
    for source in list_l1:
        dirname, filename = os.path.split(source)
        if not os.path.exists(f'{dest}/{dirname}'):
            os.makedirs(f'{dest}/{dirname}')
        shutil.copy(source, f'{dest}/{source}')
    

    【讨论】:

    • 对不起,我是 python 新手,因为我不知道所有模块。您能否简要介绍或提供样品 sn-p?
    • 文件“sme1.py”,第 8 行如果不是 os.path.exists(f'{dest}/{dirname}'): ^ SyntaxError: invalid syntax
    • 你用的是什么版本的python?在我的回答中,我使用的是至少需要 python 3.6 的 f 字符串。如果您使用的是 python
    【解决方案2】:

    您可以尝试先创建如下目录或其他库。

    import shutil
    from pathlib import Path
    
    list_l1 = ['./A/Aa/hello1.c', './B/Aa/hello1.c']
    new_parent = './C'
    
    for source in list_l1:
        path_list = source.split('/')
        file = path_list.pop()
        new_path = path_list.pop(0)
        dirs = '/'.join(path_list)
        p = new_parent + '/' + dirs  + '/'
        path = Path(p)
        path.mkdir(parents=True, exist_ok=True)
        shutil.move(source, p)
    

    【讨论】:

    • 使用os.makedirs() 如我之前的回答中所述更简洁。
    • 你是对的@jamesoh。我只是认为这可以提供另一种选择。
    猜你喜欢
    • 1970-01-01
    • 2018-03-11
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    相关资源
    最近更新 更多