简体   繁体   中英

How to rename files in directory with its sha1 hash with python?

I need to rename my files in directory with its hash with Python. I've done the same thing using 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());
            }

Can someone help me get started with what I'd use in Python to accomplish the same? I'll be using Ubuntu, if it makes any difference.

In Python if you want to compute some hash (MD5, SHA1) there is hashlib module. To make some operations on filesystem there is os module. In those modules you will find: sha1 object with hexdigest() method and listdir() and rename() functions. Example code:

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)

Attention : sha1_file() function read whole file at once so it will not work very well for huge files. As a homework try to improve it for such files (read file in parts and update hash with those parts).

Of course if fn.endswith('.sha'): is used for test purposes only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM