Python-文件处理-b模式w操作模式

with open(r"h.txt",mode="bw") as bw:
bw.write("哈哈哈hhh".encode("utf-8")) #python3解释器使用utf-8格式读取,所以打开h.txt显示正常
#文件copy工具
src_file_path=input("请输入要复制的文件路径:").strip()
dst_file_path=input("请输入要复制新的文件路径:").strip()
with open(r'{}'.format(src_file_path),mode="br") as tr,open(r'{}'.format(dst_file_path),mode="bw") as tw:
# res=tr.read() #如果从硬盘读取的数据比较大,会撑爆内存的
# tw.write(res)
#使用for循环逐行读取每一行数据
for line in tr: #for循环每次逐行读取文件一行,写入到新的文件中
tw.write(line)
#循环读取文件
#方式一: while循环
with open(r"dba.png",mode="br") as br1:
while True:
res=br1.read(1024) #读取1024字节
#print(type(res))
#<class 'bytes'>
if len(res) == 0: #len(res)是bytes类型的长度
break
print(res,len(res))

with open(r"dba.png", mode="br") as br1:
while True:
res = br1.read(1024)
if not res: #如果res读取为空,就是None(代表隐式布尔值False),not(就是把紧跟其后的那个条件结果取反) not False变成True,所以if条件是True,才会被执行
break
print(res, len(res))

#方式二:for循环
with open(r"c.txt",mode="tr",encoding="utf-8") as tr:
for line in tr: #文本文件怎么区分每一行:使用换行符\n进行区分每一行
#print(len(line)) #查看每一行的长度
print(line)

with open(r"c.txt",mode="br") as br:
for line in br: #在b模式下读文本文件还是以换行符\n进行每一行区分
print(line)
# b'\xe6\x88\x91\xe5\x93\x881\r\n'
# b'\xe6\x88\x91\xe5\x93\x882\r\n'
# b'\xe6\x88\x91\xe5\x93\x883\r\n'
with open(r"dba.png",mode="br") as br1:
for line in br1: #在b模式下读视频图片还是以换行符\n进行每一行区分
print(line)
 


 
posted @ 2020-08-31 15:17  梁博客  阅读(331)  评论(0)    收藏  举报