文件处理,二进制格式、copy小程序总结

时间:2020-12-21 20:13:26
文件处理:
文件的打开模式b模式

#1、与t模式类似不能单独使用因为单独的r、w、a是mode默认为字符串‘t’,所以必须是rb,wb,ab
#2、b模式下读写都是以bytes单位的
#3、b模式下一定不能指定encoding参数


#rb模式:只读二进制模式
# with open('xxx.jpg',mode='rb',) as f:
# data=f.read()
# print(data,)
# print(type(data))

# with open('db.txt',mode='rb',) as f:
# data=f.read() #
# print(data.decode('utf-8')) #bytes-----unicode
# print(type(data))


#wb模式:只写二进制模式
# with open('b.txt',mode='wb') as f:
# msg='你好啊,xxx'
# f.write(msg.encode('gbk'))
# with open('b.txt',mode='wb') as f:
# msg='你好啊,xxx'
# f.write(msg.encode('utf-8'))

# with open('xxx.txt',mode='rb') as f:
# data=f.read()
# # print(type(data))
# print(data.decode('utf-8'))
# with open('x.jpg',mode='rb') as f:
# data=f.read()
# print(type(data))
# print(data.decode('utf-8'))


#ab模式:二进制追加模式
# with open('x.txt',mode='ab') as f:
# f.write('你好'.encode('utf-8'))


# with open('xxx.jpg','rb') as f:
# for line in f:
# print(line)


#可读可写:r+t
# with open('x.txt','r+t',encoding='utf-8') as f:
# # print(f.readable())
# # print(f.writable())
# print(f.readline())
# f.write('\nxxxxxxxxxxxxxx\n')



#w+t:可写可读
#a+t:追加可写可读

#偏移光标:
# with open('user.txt','r+',encoding='utf-8') as f:
# f.seek(6) #偏移量的单位是字节
# # print(f.tell())
# print(f.read())



# with open('user.txt','r+',encoding='utf-8') as f:
# f.seek(6) #偏移量的单位是字节
# # print(f.tell())
# f.write('[稻衍田鸡]')


#1、先把文件内容全部读入内存
#2、然后在内存中完成修改
#3、再把修改后的结果覆盖写入原文件
#缺点:会在文件内容过大的情况下,占用过多的内存


# with open('user.txt',mode='r',encoding='utf-8') as f:
# data=f.read()
# data=data.replace('稻衍田鸡','刘锦[比egon还帅的男人]')
#
# with open('user.txt',mode='w',encoding='utf-8') as f:
# f.write(data)


#修改文件方式二:
#1、以读的方式打开原文件,以写的方式打开一个新文件
# import os
#
# with open('user.txt',mode='rt',encoding='utf-8') as read_f,\
# open('user.txt.swap',mode='wt',encoding='utf-8') as write_f:
#
# for line in read_f:
# if '成群' in line:
# line=line.replace('成群','锦[比egon还帅的男人]')
#
# write_f.write(line)

os.remove('user.txt')
os.rename('user.txt.swap','user.txt')