gpt4 book ai didi

python - 如果文本文件引用不存在的文件,则删除它们

转载 作者:行者123 更新时间:2023-12-01 01:48:00 25 4
gpt4 key购买 nike

我有一个文本文件 ( images1.txt ),其中包含 .jpg 列表名称,我有一个文件夹( Bones ),其中包含 .jpg图片。所有图像名称均为 42 个字符(包括文件扩展名),并且每个图像名称都位于单独的行上,其中包含名称和有关图像的一些信息。例如:

OO75768249870G_2018051_4A284DQ0-011628.jpg,1A4502432KJL459265,emergency
OO75768249870G_2018051_4A284DQ0-011629.jpg,1A451743245122,appointment

.jpg 之后的所有内容是我对这些照片的个人笔记。 Bones包含 images1 中命名的 4,000 多张图像中的许多图像但不是所有的。使用命令提示符或 python,如何删除 images1 中的行对应于我的 Bones 中不存在的图像文件夹?

谢谢!

最佳答案

在Python中:

import os

LEN_OF_FILENAME = 42

with open('images1.txt', 'r') as image_file:
with open('filtered_images1.txt', 'w') as filtered_image_file:
for line in image_file:
image_name = line[:LEN_OF_FILENAME]
path_to_image = os.path.join('Bones', image_name)
if os.path.exists(path_to_image):
filtered_image_file.write(line)

假设 images1.txtBones 位于同一文件夹中,如果您在该文件夹中运行上述 Python 脚本,您将获得 filtered_images1.txt.它只会包含在 Bones 中具有相应图像的行。

关于python - 如果文本文件引用不存在的文件,则删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51033194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com