python怎么判断文件大小(python3实现指定目录下文件sha256及文件大小统计)
类别:脚本大全 浏览量:1958
时间:2022-01-25 00:11:28 python怎么判断文件大小
python3实现指定目录下文件sha256及文件大小统计有时会统计某个目录下有哪些文件,每个文件的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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持开心学习网。
原文链接:https://blog.csdn.net/fengbingchun/article/details/86665247
热门推荐
- dedecms怎样快速找到图片位置(dede搬家后路径变化批量替换图片路径避免图片不能正常显示)
- vue怎么接收后台的数据(Vue封装全局toast组件的完整实例)
- mac怎么用ftp传文件(Mac自带FTP工具怎么使用 Mac自带FTP工具用法教程)
- 自定义ui组件的三个重要方法(AmazeUI 面板的实现示例)
- python pyqt 教程(Python+PyQt5实现美剧爬虫可视工具的方法)
- python使用教程操作(详解python中@的用法)
- php如何继承多个类(PHP面向对象程序设计子类扩展父类子类重新载入父类操作详解)
- python什么是深拷贝什么是浅拷贝(Python深拷贝与浅拷贝用法实例分析)
- 选择哪个平台注册虚拟主机好(怎么选择好的便宜云虚拟主机?分享挑选便宜云虚拟主机的小技巧)
- CSS中margin和padding的区别