Reputation: 3070
I have a folder image (JPGE_Image) that contains jpg images as follows:
1.jpg
2.jpg
3.jpg
...
100.jpg
I have other text file which contains the path of these selected jpeg images (not all images, just selected as 1.jpg, 3.jpg...) as
/home/users/JPGE_Image/1.jpg
/home/users/JPGE_Image/3.jpg
/home/users/JPGE_Image/5.jpg
...
/home/users/JPGE_Image/99.jpg
I want to copy selected image in the text file to other folder named Selected_Folder
. How could I do it in python 2.7. Thank all. This is what I tried, but it does not get information from text file
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)
Upvotes: 0
Views: 1561
Reputation: 46759
You just need to apply your logic on a line by line basis as follows:
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)
As you read each line, use strip()
to remove the trailing newline. Then use os.path.split()
to get just the filename of the source. This can then be joined to your dstdir
.
Upvotes: 2
Reputation: 39
You can read the paths from txt file line by line, like this:
with open(txtfile_path) as f:
for srcfile in f:
shutil.copy(srcfile, dstdir)
Upvotes: 3