def sum_file_md5(file_path, offset=0, end=None):
"""
获取文件md5
:param file_path: 文件路径
:param offset:
:param end:
:return:
"""
md5 = hashlib.md5()
with open(file_path, "rb") as f:
f.seek(offset, 0)
if end is None:
md5.update(f.read())
else:
md5.update(f.read(end - offset + 1))
return md5.hexdigest()
def del_file(file_path):
system = platform.system()
if system == "Windows":
os.system("DEL %s" % (file_path))
elif system == "Linux":
os.system("rm %s" % (file_path))
def random_write_file(save_file, target_file, position, src_file):
"""
save_file: 随机写后新保存的文件
target_file: 被随机写的文件
postion: 开始写的起始位置,从0开始
src_file: 需要写的内容
单位按byte
"""
if os.path.getsize(src_file) + position > os.path.getsize(target_file):
return "随机写越界"
with open(save_file, "wb") as save_file_io:
with open(target_file, "rb") as target_file_io:
save_file_io.write(target_file_io.read(position))
with open(src_file, "rb") as src_file_io:
save_file_io.write(src_file_io.read())
target_file_io.seek(position + os.path.getsize(src_file))
save_file_io.write(target_file_io.read())
def combos_files(des_file, file_arg):
"""
des_file: 合并后的文件路径
file_arg: [(file_path_1, offset, length), (file_path_1, offset, length)]
"""
with open(des_file, "wb") as f:
for file, offset, length in file_arg:
with open(file, "rb") as tmp_f:
tmp_f.seek(offset, 0)
f.write(tmp_f.read(length))
def append_write_file(des_file, src_file):
"""
des_file: 被追加写的文件
src_file:需要追加写的内容
"""
with open(des_file, "ab") as des_file_io:
with open(src_file, "rb") as src_file_io:
des_file_io.write(src_file_io.read())
python 本地文件操作(modify|append|combos|MD5)