shell 如何修复文件扩展名和删除重复项

shell how to fix file extension and remove duplicate

我使用 wget 命令从 imagenet 文件提供的 url 下载了很多文件(here 是汽车图像的一个例子)。但是当我检查我的文件时,我发现很多文件,都有错误的扩展名。例如,在这些文件中,扩展名为“.jpg”的文件实际上是一个文本文件。而且我知道 --adjust-extension 可能只适用于 .html 和 .css 文件。

所以我的问题是那些文件:1. 我怎样才能恢复文件的扩展名(包括.jpg、.txt、.png、.html 等)? 2.有些图片可能下载了不止一次,如何去重?

能做到python也行。 提前致谢。

您可以使用像 python-magic https://github.com/ahupp/python-magic or filemagic https://pypi.python.org/pypi/filemagic 这样的包,它提供了根据内容识别文件的方法。 unix file 命令也用 --mime-type 标志来查找文件类型。

至于重复,有很多实用程序可以执行此操作,但是在 python 中执行此操作会像这样:

import os, hashlib

def remove_dupes(dir):
    unique = set()
    for filename in os.listdir(dir):
        if os.path.isfile(filename):
            filehash = hashlib.sha1(file(filename).read()).hexdigest()
            if filehash not in unique: 
                unique.add(filehash)
            else: 
                os.remove(filename)

您可以使用file 程序根据文件内容而不是文件名来判断文件类型。文件几乎随 linux 和 unix 的每个版本一起提供,包括 BSD 和 OSX。如果您使用 Windows,我认为它包含在 Cygwin 中。

使用标志 -i 您将获得作为 mimetype 的输出,并且您可以使用标准库中的 mimetypes 模块将 mimetype 映射到适当的文件扩展名。这适用于许多文件类型。

此示例在 linux 中使用 python 3。它将输出当前目录中的每个文件和可能的文件扩展名列表。

import os, mimetypes, subprocess
for filename in os.listdir(): 
    mime = subprocess.check_output(['file', '-ib', filename]).decode().split(';')[0]
    print(filename, mimetypes.guess_all_extensions(mime.strip()))