如何用Python将目录中的文件重命名为其SHA1哈希?

-1 投票
1 回答
2365 浏览
提问于 2025-04-16 11:30

我想用Python把目录里的文件重命名为它们的哈希值。我之前用C#做过同样的事情:

   Console.Write("enter path");
        string path = Console.ReadLine();

        foreach (var i in Directory.GetFiles(path))
        {
            try
            {
                using (SHA1Managed sha1 = new SHA1Managed())
                {
                    FileStream f = new FileStream(i.ToString(), FileMode.Open);
                    byte[] hash = sha1.ComputeHash(f);
                    string formatted = string.Empty;
                    foreach (byte b in hash)
                    {
                        formatted += b.ToString("X2");
                    }
                    f.Close();

                    File.Move(i.ToString(), path+"//" + formatted);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(i.ToString());
            }

有没有人能帮我一下,告诉我在Python中该怎么开始做这个?我会在Ubuntu系统上操作,如果这有什么影响的话。

1 个回答

4

在Python中,如果你想计算一些哈希值(比如MD5或SHA1),可以使用hashlib模块。要在文件系统上进行一些操作,可以使用os模块。在这些模块里,你会找到:sha1对象,它有一个叫hexdigest()的方法,还有listdir()rename()这两个函数。下面是一个示例代码:

import os
import hashlib

def sha1_file(fn):
    f = open(fn, 'rb')
    r = hashlib.sha1(f.read()).hexdigest()
    f.close()
    return r

for fn in os.listdir('.'):
    if fn.endswith('.sha'):
        hexh = sha1_file(fn)
        print('%s -> %s' % (fn, hexh))
        os.rename(fn, hexh)

注意sha1_file()函数会一次性读取整个文件,所以对于很大的文件,它的效果不好。作为作业,试着改进这个函数,让它能处理大文件(分块读取文件,并用这些块来更新哈希值)。

当然,if fn.endswith('.sha'):这行代码只是用来测试的。

撰写回答