Reputation: 2422
I have several image names in my directory that I want to read.
sq_of_images = listdir('images/sequence1/')
sq_of_images = [img for img in sq_of_images if img.endswith(".jpg")]
print(sq_of_images)
['im_001.jpg', 'im_002.jpg', 'im_003.jpg', 'im_004.jpg', 'im_005.jpg', 'im_006.jpg', 'im_007.jpg', 'im_008.jpg', 'im_009.jpg', 'im_010.jpg', 'im_011.jpg', 'im_012.jpg', 'im_013.jpg', 'im_014.jpg', 'im_015.jpg', 'im_016.jpg', 'im_017.jpg', 'im_018.jpg', 'im_019.jpg', 'im_020.jpg', 'im_021.jpg', 'im_022.jpg', 'im_023.jpg', 'im_024.jpg', 'im_025.jpg', 'im_026.jpg', 'im_027.jpg', 'im_028.jpg', 'im_029.jpg', 'im_030.jpg'] 30
I'd like to append the folder path to the images as well but can't figure out how to do it. Typing it this way gives me an error.
sq_of_images = ['images/', img for img in sq_of_images if img.endswith(".jpg")]
Upvotes: 1
Views: 136
Reputation: 31339
Although you can use simple string concatenation 'images/' + img
, there is an os
submodule for handling paths which is called path
. You can use os.path.join
to join paths:
from os import path
sq_of_images = [path.join('images/', img) for img in sq_of_images if img.endswith(".jpg")]
Upvotes: 2
Reputation: 1696
You can concatenate strings using plus sign instead of comma:
sq_of_images = ['images/' + img for img in sq_of_images if img.endswith(".jpg")]
You also can insert multiple fields into a string using format
:
sq_of_images = [
'{img_folder}/{img_name}'.format(img_folder='images', img_name=img)
for img in sq_of_images if img.endswith(".jpg")]
Of course you can also use the join function like Reut Sharabani proposed in his answer, I really like that approach more than operating with string methods because it is more robust.
Upvotes: 1