如何快速从一个目录切换到另一个目录Python
How to rapidly switch from one directory to another Python
我在一个目录中有一个巨大的图像列表,在另一个目录(.txt 文件)中有另一个相应的注释列表。
我需要按照匹配的图像注释对每个图像执行操作并将其保存到另一个目录中。有没有一种优雅的方法可以不在每一步 chdir 三次?
也许使用 cPickle 或任何用于快速文件管理的库?
import glob
from PIL import Image
os.chdir('path_images')
list_im=glob.glob('*.jpg')
list_im.sort()
list_im=path_images+list_im
os.chdir('path_txt')
list_annot=glob.glob('*.txt')
list_annot.sort()
list_annot=path_txt+list_im
for i in range(0,len(list_images)):
Joel 指出,如果您在名称中包含路径,则 os 操作不是强制性的
#os.chdir('path_images')
im=Image.open(list_im[i])
#os.chdir('path_text')
action_on_image(im,list_annot[i])
#os.chdir('path_to_save_image')
im.save(path_to_save+nom_image)
我是 Python 的真正初学者,但我相信我的代码非常低效并且可以改进。
您不必 chdir
(顺便说一句,您真的不想依赖于当前工作目录)。在你的代码中到处使用绝对路径,你会没事的。
import os
import glob
from PIL import Image
abs_images_path = <absolute path to your images directory here>
abs_txt_path = <absolute path to your txt directory here>
abs_dest_path = <absolute path to where you want to save your images>
list_im=sorted(glob.glob(os.path.join(abs_images_path, '*.jpg')))
list_annot=sorted(glob.glob(os.path.join(abs_txt_path, '*.txt')))
for im_path, txt_path in zip(list_im, list_annot):
im = Image.open(im_path)
action_on_image(im, txt_path)
im.save(os.path.join(abs_dest_path, nom_image))
请注意,如果您的路径是相对于脚本安装位置的路径,则可以使用 os.path.dirname(os.path.abspath(__file__))
获取脚本的目录路径
我在一个目录中有一个巨大的图像列表,在另一个目录(.txt 文件)中有另一个相应的注释列表。
我需要按照匹配的图像注释对每个图像执行操作并将其保存到另一个目录中。有没有一种优雅的方法可以不在每一步 chdir 三次?
也许使用 cPickle 或任何用于快速文件管理的库?
import glob
from PIL import Image
os.chdir('path_images')
list_im=glob.glob('*.jpg')
list_im.sort()
list_im=path_images+list_im
os.chdir('path_txt')
list_annot=glob.glob('*.txt')
list_annot.sort()
list_annot=path_txt+list_im
for i in range(0,len(list_images)):
Joel 指出,如果您在名称中包含路径,则 os 操作不是强制性的
#os.chdir('path_images')
im=Image.open(list_im[i])
#os.chdir('path_text')
action_on_image(im,list_annot[i])
#os.chdir('path_to_save_image')
im.save(path_to_save+nom_image)
我是 Python 的真正初学者,但我相信我的代码非常低效并且可以改进。
您不必 chdir
(顺便说一句,您真的不想依赖于当前工作目录)。在你的代码中到处使用绝对路径,你会没事的。
import os
import glob
from PIL import Image
abs_images_path = <absolute path to your images directory here>
abs_txt_path = <absolute path to your txt directory here>
abs_dest_path = <absolute path to where you want to save your images>
list_im=sorted(glob.glob(os.path.join(abs_images_path, '*.jpg')))
list_annot=sorted(glob.glob(os.path.join(abs_txt_path, '*.txt')))
for im_path, txt_path in zip(list_im, list_annot):
im = Image.open(im_path)
action_on_image(im, txt_path)
im.save(os.path.join(abs_dest_path, nom_image))
请注意,如果您的路径是相对于脚本安装位置的路径,则可以使用 os.path.dirname(os.path.abspath(__file__))