Python文件操作之二进制文件详解
更新时间:2021年09月27日 16:52:00 作者:Tester_Cheng
下面小编就为大家带来一篇使用Python文件操作之二进制文件。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
1.二进制读取模式
- rt 读取文本文件(默认值)
- rb 读取二进制文件
file_name = "C:/Users/cheng/Desktop/can.jmx"
with open(file_name, 'rt', ) as can:
print(can.read())
执行结果

rb读取模式
file_name = "C:/Users/cheng/Desktop/can.jmx"
with open(file_name, 'rb', ) as can:
print(can.read())
执行结果

- 读取100字节
file_name = "C:/Users/cheng/Desktop/can.jmx"
with open(file_name, 'rb', ) as can:
#读取文本文件,size是以字符为单位的
#读取二进制文件,size是以字节为单位的
print(can.read(100))
执行结果

将读取到的内容写入到文件
file_name = "C:/Users/cheng/Desktop/can.jmx"
with open(file_name, 'rb', ) as can:
# 定义一个新的文件
new_name = 'to.jmx'
with open(new_name, 'wb') as cheng:
# 定义每次读取的大小
cc = 1024 * 100
while True:
# 从已有对象中读取数据
content = can.read(cc)
#内容读取完毕,终止循环
if not content:
break
#将读取到的数据写入到新对象中
cheng.write(content)
执行结果:


总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!
相关文章
Python 中如何使用 setLevel() 设置日志级别
这篇文章主要介绍了在 Python 中使用setLevel() 设置日志级别,Python 提供了一个单独的日志记录模块作为其标准库的一部分,以简化日志记录,本文将讨论日志记录 setLevel 及其在 Python 中的工作方式,需要的朋友可以参考下2023-07-07


最新评论