【问题标题】:How to delete from a container of strings of paths, duplicate filenames together with their different paths?如何从路径字符串的容器中删除,重复的文件名及其不同的路径?
【发布时间】:2020-07-20 14:51:36
【问题描述】:

我需要删除文件列表(或文件集)中的重复文件,这些文件将被复制到 Python 中按日期专门创建的文件夹中。

我需要的是找到已经在起始列表中的副本,在文件路径'/home/user/text.txt'的最后一部分,然后从列表中删除整个路径,以便开始将被复制的文件列表(或集合)没有文件系统中可能存在的那些重复项,并且要复制的元素数量(在起始容器中表示)最终与实际复制的文件数量相同在目标文件夹中。

我也尝试通过key 的选项sorted() 来达到这个目标:

set_path_filename_without_duplicates = sorted(set_path_filename,
                                              key=lambda x: x.split()[1])

我收到错误IndexError: list index out of range

目前我还不知道该怎么做,有人有想法吗?

【问题讨论】:

  • 请将文件列表(或集合)中的一些数据示例添加到您的问题中。

标签: python path duplicates containers


【解决方案1】:

所以如果我理解正确的话,你有很多文件的列表。列表中的文件可能有重复,但同一个文件可能有很多地方?

如果是这样,以下应该可以为每个唯一文件名仅返回一个路径。

import os
list_of_filepaths=['root/dir/some_pic.jpeg',
               'root/dir/some_pic2.jpeg',
               'root/documents/budget.excl',
               'root/Music/audio.mp3',
               'root/dir/some_pic.jpeg',
               'root/otherfolder/some_pic.jpeg']

dict_of_files={os.path.basename(file):file for file in list_of_filepaths}
files=list(set(dict_of_files.keys()))
unique_files=[dict_of_files[file] for file in files]

In [16]: unique_files
Out[16]: 
['root/dir/some_pic2.jpeg',
 'root/documents/budget.excl',
 'root/Music/audio.mp3',
 'root/otherfolder/some_pic.jpeg']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    相关资源
    最近更新 更多