如何从 .txt 文件中的路径打开图像?
How to Open Images From a Path In a .txt File?
如果我有一个文本文件,其中包含我计算机上图像的完整目录行,例如:
F:\DESKTOP\images\def456.jpg
F:\DESKTOP\images\abc123.jpg
C:\Users\Me\Downloads\orange.jpg
C:\Users\Me\Downloads\apple.jpg
,我如何通过使用 PIL 模块读取 .txt 文件中的行来让 Python3 打开它们?比方说,我只是从一些类似的开始:
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()
如果 .txt 文件只有 1 行,上面的代码就可以工作,但是我该怎么做才能通读并打开多行?谢谢!
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)
在 .txt
文件中,删除多余的行并使路径一个接一个地排列。
示例:
F:\DESKTOP\images\def456.jpg
F:\DESKTOP\images\abc123.jpg
....
现在您可以使用split()
方法了。
所以你的主要代码应该是这样的:
# 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)
更多关于 python split()
方法:
https://www.geeksforgeeks.org/python-string-split/
如果我有一个文本文件,其中包含我计算机上图像的完整目录行,例如:
F:\DESKTOP\images\def456.jpg
F:\DESKTOP\images\abc123.jpg
C:\Users\Me\Downloads\orange.jpg
C:\Users\Me\Downloads\apple.jpg
,我如何通过使用 PIL 模块读取 .txt 文件中的行来让 Python3 打开它们?比方说,我只是从一些类似的开始:
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()
如果 .txt 文件只有 1 行,上面的代码就可以工作,但是我该怎么做才能通读并打开多行?谢谢!
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)
在 .txt
文件中,删除多余的行并使路径一个接一个地排列。
示例:
F:\DESKTOP\images\def456.jpg
F:\DESKTOP\images\abc123.jpg
....
现在您可以使用split()
方法了。
所以你的主要代码应该是这样的:
# 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)
更多关于 python split()
方法:
https://www.geeksforgeeks.org/python-string-split/