简体   繁体   English

将文件连同文件路径从列表复制到文件夹或其他路径

[英]Copy files along with file paths from a list to a folder or another path

I have a list containing files along with their paths.我有一个包含文件及其路径的列表。 I need to copy or move the files with their entire path into another directory or folder.我需要将文件及其整个路径复制或移动到另一个目录或文件夹中。

I have tried as follows but path unable to copy the path and only files are being copied.我已尝试如下,但路径无法复制路径,并且仅复制文件。

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/')

You probably want to use os.makedirs() to make the nested directories.您可能想使用os.makedirs()来制作嵌套目录。 You might want to separate the paths in your list_l1 into directory and filename parts first, and use os.path.exists() to check if the directory exists before attempting to create it.您可能希望list_l1中的路径分成目录和文件名部分,然后在尝试创建目录之前使用os.path.exists()检查目录是否存在。

You could try:你可以试试:

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}')

You can try making the directories first like below or some other library.您可以尝试首先创建目录,如下所示或其他一些库。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将所有文件从txt文件的路径复制到文件夹? - How to copy all files to a folder from path in a txt file? 如何将从 txt 文件中选择的文件复制到另一个文件夹 python - How to copy files selected from a txt file to another folder python 将文件从一个文件夹复制到另一个在 .txt 文件中具有匹配名称的文件夹 - Copy files from one folder to another with matching names in .txt file 如何找到jpg。 从给定文件夹列表中的文件复制到另一个文件夹位置? - How can I find jpg. files from a list for a given folder and copy them to another folder location? 每 1 小时将文件从一个文件夹复制到另一个文件夹 - copy files from a folder to another every 1 hour 在python中使用哪种文件shutil复制方法将某些文件从一个文件夹复制到另一个文件夹? - Which file shutil copy method to use in python to copy certain files from one folder to another? 如何从文件路径列表中打开文件 - How to open files from a list of file paths 从python文件路径列表中加载文件 - Load files from a list of file paths in python 如何将奇数文件从一个文件夹复制到另一个文件夹? - How to copy odd numbered Files from one folder to another folder? 将文件从 Windows 文件夹树复制到另一个文件夹 - Copy files from Windows folder tree to another folder
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM