189 8069 5689

python3实现指定目录下文件sha256及文件大小统计-创新互联

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

成都创新互联是少有的成都做网站、成都网站制作、营销型企业网站、重庆小程序开发公司、手机APP,开发、制作、设计、买友情链接、推广优化一站式服务网络公司,成立与2013年,坚持透明化,价格低,无套路经营理念。让网页惊喜每一位访客多年来深受用户好评
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()

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享题目:python3实现指定目录下文件sha256及文件大小统计-创新互联
本文来源:http://jkwzsj.com/article/idgjd.html

其他资讯