如何使用python使用sha1哈希重命名目录中的文件?
我需要用Python重命名目录中的文件及其散列。我用C做了同样的事情:如何使用python使用sha1哈希重命名目录中的文件?,python,hash,Python,Hash,我需要用Python重命名目录中的文件及其散列。我用C做了同样的事情: Console.Write("enter path"); string path = Console.ReadLine(); foreach (var i in Directory.GetFiles(path)) { try { using (SHA1Managed sha1 = new S
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。在Python中,如果你想计算一些散列MD5,SHA1有一个模块。 要在文件系统上进行一些操作,有一个模块。在这些模块中,您将找到: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_文件函数一次读取整个文件,因此对于大文件它不会很好地工作。作为一个家庭作业,试着对这些文件进行改进,读取部分文件并用这些部分更新散列
当然,如果fn.endswith'.sha':仅用于测试目的。首先,为什么不在Ubuntu下编译您的C代码?它会运行得很好。第二,你的具体问题是什么?你试过什么?这不是一个免费的代码转换网站,它雇佣人类来为你思考。我同意吉姆的观点:你有C代码,为什么要转换它,当你可以运行它的时候。Mono可能并不完美,但我很确定它会很好地运行这些代码。如果你不转换,请为我提供链接文章示例!!我应该用python编写它