如何从txt文件中的路径将所有文件复制到文件夹?

时间:2017-01-04 06:59:29

标签: python python-2.7

我有一个包含jpg图像的文件夹图像(JPGE_Image),如下所示:

1.jpg
2.jpg
3.jpg
...
100.jpg

我有其他文本文件,其中包含这些所选jpeg图像的路径(并非所有图像,仅选择为1.jpg,3.jpg ...)

/home/users/JPGE_Image/1.jpg
/home/users/JPGE_Image/3.jpg
/home/users/JPGE_Image/5.jpg
...
/home/users/JPGE_Image/99.jpg

我想将文本文件中的选定图像复制到名为Selected_Folder的其他文件夹中。我怎么能在python 2.7中做到这一点。谢谢大家。这是我尝试过的,但它没有从文本文件中获取信息

import os
import shutil

srcfile = '/home/users/JPGE_Image/1.jpg'
dstroot = '/home/users/Selected_Folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

2 个答案:

答案 0 :(得分:3)

您可以逐行读取txt文件中的路径,如下所示:

with open(txtfile_path) as f:
    for srcfile in f:
        shutil.copy(srcfile, dstdir)

答案 1 :(得分:2)

您只需要逐行应用逻辑,如下所示:

node-jwt-simple

在阅读每一行时,使用import os import shutil text_file_list = 'my_text_file.txt' dstroot = '/home/users/Selected_Folder' try: os.makedirs(dstroot) except OSError as e: # catch exception if folder already exists pass with open(text_file_list) as f_input: for srcfile_path in f_input: srcfile_path = srcfile_path.strip() srcfile = os.path.split(srcfile_path)[1] dstdir = os.path.join(dstroot, srcfile) shutil.copy(srcfile_path, dstdir) 删除尾随换行符。然后使用strip()来获取源的文件名。然后,您可以将其加入os.path.split()

相关问题