用python3实现指定目录下文件sha256及文件大小统计
生活随笔
收集整理的這篇文章主要介紹了
用python3实现指定目录下文件sha256及文件大小统计
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有時會統計某個目錄下有哪些文件,每個文件的sha256及文件大小等相關信息,這里用python3寫了個腳本用來實現此功能,此腳本可跨平臺,同時支持windows和linux,腳本(get_dir_file_info.py)內容如下:
import os
import sys
import hashlibdef 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 resultdef CalcFileSha256(filname):''' calculate file sha256 '''with open(filname, "rb") as f:sha256obj = hashlib.sha256()sha256obj.update(f.read())hash_value = sha256obj.hexdigest()return hash_valuedef CalcFileSize(filename):''' calculate file size '''return os.stat(filename).st_sizedef 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 resultdef 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:https://github.com/fengbingchun/Python_Test
總結
以上是生活随笔為你收集整理的用python3实现指定目录下文件sha256及文件大小统计的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 提高C++性能的编程技术笔记:总结
- 下一篇: 对象检测工具包mmdetection简介