最近有这么一个场景,我远程连接了公司的电脑,但是公司禁用了文件的复制粘贴,只能进行文字复制粘贴,而想要将里面的文件拷贝到外面则需要将文件进行转码,复制到本机再转回源文件,这里用到base64编码进行处理
将文件进行base64编码
# save_as_base64.py
import base64
def file_to_base64(file_path, output_txt_path):
with open(file_path, 'rb') as file:
file_data = file.read()
base64_text = base64.b64encode(file_data).decode('utf-8')
with open(output_txt_path, 'w') as txt_file:
txt_file.write(base64_text)
print(f"Base64 文本已保存到: {output_txt_path}")
# 使用示例
file_to_base64(
file_path=r"1.docx", # 替换为实际文件路径
output_txt_path=r"output.txt" # 生成的Base64文本路径
)
将base64还原为文件
# restore_from_base64.py
import base64
def base64_to_file(base64_txt_path, output_file_path):
with open(base64_txt_path, 'r') as txt_file:
base64_text = txt_file.read()
file_data = base64.b64decode(base64_text.encode('utf-8'))
with open(output_file_path, 'wb') as file:
file.write(file_data)
print(f"文件已还原到: {output_file_path}")
# 使用示例
base64_to_file(
base64_txt_path=r"output.txt", # 替换为保存的Base64文本路径
output_file_path=r"1.docx" # 还原的文件路径
)
注意事项
需要注意的是,单个base64文件不能超过10M,否则还原的时候会报错。如果遇到超过10M的文件,建议先用7z的分卷压缩,将其拆分为多个文件,每个文件解码后再解压为单个文件