Home > Back-end >  How to Open Images From a Path In a .txt File?
How to Open Images From a Path In a .txt File?

Time:12-14

if I had a text file that just had lines of full directories to images on my machine eg:

F:\DESKTOP\images\def456.jpg

F:\DESKTOP\images\abc123.jpg

C:\Users\Me\Downloads\orange.jpg

C:\Users\Me\Downloads\apple.jpg

, how could I get Python3 to open them by reading the lines in the .txt file using the PIL module? Let's say I'm just starting with some like:

import os
from PIL import Image

f = open("C:\\Users\\Me\\images.txt", "r")
##images.txt is the file with the paths of the images

a = (f.read())

im = Image.open(a)

im.show() 

Above code works if the .txt file only had 1 line, but how would I do it to read through and open multiple lines? Thanks!

CodePudding user response:

import cv2
with open('text_file.txt','rb') as f:
    img_files = [line.strip() for line in f]


for image in img_files:
    load_Image = cv2.LoadImage(image)

CodePudding user response:

In the .txt file, remove the extra lines and keep the paths one below each other. Example:

F:\DESKTOP\images\def456.jpg
F:\DESKTOP\images\abc123.jpg
....

Now you can use the split() method. So your main code should look like this:

# Import modules
import os

f = open("C:\\Users\\Me\\images.txt", "r")
##images.txt is the file with the paths of the images

a = f.read()    # read the txt file
a = a.split("\n")
# Splitting the string, such that each new line is an item in list 'a'.

for path in a:
    if path != '' and os.path.exists(path):
        os.startfile(path)

More about python split() method: https://www.geeksforgeeks.org/python-string-split/

  • Related