删除具有相同名称部分的文件

发布于 2025-02-13 17:30:35 字数 611 浏览 0 评论 0原文

我正在尝试浏览我的图像目录并删除重复的图像。但是,我想递归浏览目录,并删除与文件名相同日期的第二张图像。当我列出文件时,我要这样做:

my_current_image_path = r'../Desktop/Images/city1'
for f in sorted(listdir(my_current_image_path)):
    print(f)

我将获得此输出:

20190602_051825_Visual.tif
20190604_052001_Visual.tif
20190605_044324_Visual.tif
20190605_052033_Visual.tif
20190607_044351_Visual.tif
20190607_051806_Visual.tif
20190611_051850_Visual.tif

第3和第4个条目在同一天(05),第五和第6个条目在同一天(07)(文件名读取为:date_time_visual.tif) )。我希望能够使用某种观察图像文件的循环,以及下一个图像文件,然后在看到文件名的一天匹配的一天部分时,删除了额外的映像(可能带有OS.Remove),但是我不确定该怎么做。任何帮助都将受到赞赏。

I am trying to go through my image directories and delete duplicate images. However, I want to recursively go through my directories and delete the second image that has the same date as the file name. When I list the files out I do this:

my_current_image_path = r'../Desktop/Images/city1'
for f in sorted(listdir(my_current_image_path)):
    print(f)

And i get this output:

20190602_051825_Visual.tif
20190604_052001_Visual.tif
20190605_044324_Visual.tif
20190605_052033_Visual.tif
20190607_044351_Visual.tif
20190607_051806_Visual.tif
20190611_051850_Visual.tif

The 3rd and the 4th entry have the same DAY (05), and the 5th and 6th have the same DAY (07) (filename reads as : DATE_TIME_Visual.tif). I want to be able to use some kind of loop that looks at the image file, and the next image file and then when it sees the day portion of the file name matches, removes that extra image (probably with os.remove) but I am unsure how to go about that. Any help is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陪你到最终 2025-02-20 17:30:35

使用set保留已看到的日期。如果日期已经在集合中,请删除文件。

dates = set()

for f in sorted(listdir(my_current_image_path)):
    date = f.split('_')[0]
    if date in dates:
        os.remove(os.path.join(my_current_image_path, f))
    else:
        dates.add(date)

Use a set to hold the dates that have been seen. If the date is already in the set, remove the file.

dates = set()

for f in sorted(listdir(my_current_image_path)):
    date = f.split('_')[0]
    if date in dates:
        os.remove(os.path.join(my_current_image_path, f))
    else:
        dates.add(date)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文