[英]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.