python3实现指定目录下文件sha256及文件大小统计

yipeiwu_com5年前Python基础

有时会统计某个目录下有哪些文件,每个文件的sha256及文件大小等相关信息,这里用python3写了个脚本用来实现此功能,此脚本可跨平台,同时支持windows和linux,脚本(get_dir_file_info.py)内容如下:

import os
import sys
import hashlib
 
def Usage():
 ''' usage description '''
 num = len(sys.argv)
 if num != 3:
 print("Error: please input two parameters")
 print("for example: {} path_name save_file_name".format(sys.argv[0]))
 sys.exit(1)
 
def GetFilesList():
 ''' get file list '''
 input_path_name = sys.argv[1]
 result = list()
 
 for dirpath, dirnames, filenames in os.walk(input_path_name, followlinks=True):
 for filename in filenames:
  file_path = os.path.join(dirpath, filename)
  result.append(file_path)
 
 result.sort()
 return result
 
def CalcFileSha256(filname):
 ''' calculate file sha256 '''
 with open(filname, "rb") as f:
 sha256obj = hashlib.sha256()
 sha256obj.update(f.read())
 hash_value = sha256obj.hexdigest()
 return hash_value
 
def CalcFileSize(filename):
 ''' calculate file size '''
 return os.stat(filename).st_size
 
def GetFileContent():
 ''' get file contnet '''
 files_list = GetFilesList()
 result = list()
 
 for f in files_list:
 hash = CalcFileSha256(f)
 size = CalcFileSize(f)
 file_name = os.path.basename(os.path.realpath(f))
 path_name = os.path.dirname(os.path.realpath(f))
 dictionary = {"path": path_name, "filename": file_name, "sha256": hash, "size": size}
 #print("result: {}".format(dictionary))
 result.append(dictionary)
 return result
 
def WriteToFile(contents):
 ''' write content to the specified file '''
 fp = open(sys.argv[2], "w")
 
 for content in contents:
 #print("content:", content)
 str0 = str(content)
 str1 = str0.replace("\\\\", "/")
 fp.write(str1)
 fp.write("\n")
 fp.close()
 
def ReplaceStr(src_str, new_str):
 ''' replace source string with new string '''
 contents = list()
 
 fp = open(sys.argv[2], "r")
 line = fp.readline()
 while line:
 contents.append(line)
 line = fp.readline()
 fp.close()
 
 fp = open(sys.argv[2], "w")
 for content in contents:
 str0 = content.replace(src_str, new_str)
 fp.write(str0)
 fp.close()
 
def main():
 Usage()
 WriteToFile(GetFileContent())
 ReplaceStr(" ", "")
 ReplaceStr("'", "\"")
 
if __name__ == "__main__":
 main()

执行操作如下:

执行结果及生成的prj_file_list.txt内容如下:

GitHub:Python_Test

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现屏幕截图的两种方式

使用windows API 使用PIL中的ImageGrab模块 下面对两者的特点和用法进行详细解释。 一、Python调用windows API实现屏幕截图 好处是...

Python闭包的两个注意事项(推荐)

什么是闭包? 简单说,闭包就是根据不同的配置信息得到不同的结果。 再来看看专业的解释:闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的...

python获取指定字符串中重复模式最高的字符串方法

给定一个字符串,如何得到其中重复模式最高的子字符串,我采用的方法是使用滑窗机制,对给定的字符串切分,窗口的大小从1增加到字符串长度减1,将所有的得到的切片统计结果,在这里不考虑单个字符的...

解析Python3中的Import

Python import的搜索路径 import的搜索路径为: 搜索「内置模块」(built-in module) 搜索 sys.path 中的路径 而sys.path在...

python获取代码运行时间的实例代码

有的时候,操作大文件,或者取数,要很久,我们给脚本首尾添加一段代码就知道,这段代码整体的大致运行时间了。 import time start =time.clock() #中间写上代...