python 文件操作

- 文件打开

  • 文件读写原理:文件读写俗称‘IO操作’ input output
  • 读:把文件拿到程序.py
  • 写:反过来
    ‘r’ 读
    ‘w’ 写
    ‘a’ 覆盖、重复写
    ‘rb’ / ‘wb’ 转二进制
    ‘a+’ 边写边读

- 文件操作

  • read(size) 读几个字符,若省略size则全读
  • readline() 读一行
  • readlines()
  • write(str)
  • writelines(list)
  • seek() 把文件指针挪到新的位置上,注:中文是2个字符
  • tell() 返回文件指针的当前位置
  • flush() 把缓冲区内容写入文件,但不关闭文件
  • close() 把缓冲区内容写入文件,关闭文件,释放文件对象相关资源

- with 语句(上下文管理器)

  • 上下文管理器:在一个类里,实现了特殊方法__enter__和__exit__
  • 自动关闭资源体现在:就算中间(如:show实例对象)有问题,也会执行exit关闭资源
  • with open(‘test.txt’) as f:
    print f.readlines()
    上下文表达式:with open(‘test.txt’) as f:
    上下文管理器:open(‘test.txt’)
    f 不是上下文管理器,应该是资源对象。
# 不同编码格式对于相同内容占磁盘的内存大小不同
'''文件读写原理:文件读写俗称‘IO操作’ input output
读:把文件拿到程序.py
写:反过来
python操作文件 - 打开或新建文件 - 读、写文件 - 关闭资源
'''
# 备注:txt01是手动创建的记事本,为UTF-8,txt02和txt03是在.py创建,格式为GBK(py默认)
#======================= 常用的文件打开模式
print('------------------- 读 read')
file = open('txt01.txt','r',encoding='UTF-8') # 读
print(file.readlines()) # 读取内容
file.close()

print('------------------- 写(覆盖) write')
file = open('txt02.txt','w')
file.write('中国\n')
file.close()

print('------------------- 追加反复写 a')
file = open('txt03.txt','a')
file.write('中国\t')   # 执行几次就在文件里有几个‘中国’
file.close()

print('------------------- 二进制 b,但要结合读写 wb rb')
pic1 = open('logo.png','rb')
pic2 = open('logo_copy.png','wb') # 目的:把pic1的图给pic2
pic2.write(pic1.read())
pic1.close()
pic2.close() # 我这边一run图就坏 md

print('------------------ '+' 不能单独使用,结合以上,如a+')
# 例子以后找到了再补

'''
read(size) 读几个字符,若省略size则全读
readline() 读一行
readlines() 
write(str)
writelines(list)
seek() 把文件指针挪到新的位置上,注:中文是2个字符
tell() 返回文件指针的当前位置
flush() 把缓冲区内容写入文件,但不关闭文件
close() 把缓冲区内容写入文件,关闭文件,释放文件对象相关资源
'''
#========================= 文件对象的常用方法
# 参考视频 P131
file = open('txt02.txt','r')
file.seek(2)
print(file.read())
print(file.tell())
file.close()

'''上下文管理器:在一个类里,实现了特殊方法__enter__和__exit__
自动关闭资源体现在:就算中间(如:show实例对象)有问题,也会执行exit关闭资源
with open('test.txt') as f:
    print f.readlines()
1. 上下文表达式:with open('test.txt') as f:
2. 上下文管理器:open('test.txt')
3. f 不是上下文管理器,应该是资源对象。
'''
#======================== with语句(上下文管理器)文件操作推荐
# 补充资料:https://www.cnblogs.com/wongbingming/p/10519553.html
# 原理解析:
class Resource(object):
    def __enter__(self):
        print('__enter__特殊方法被调用')
        return self  # 这句别忘写!!!

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('__exit__特殊方法被调用')

    def show(self):
        print('show')

with Resource() as res:  # 相当于 res=Resource()
    res.show() # 执行顺序:enter- show- exit,离开with,自动调用exit

with open('txt01.txt','r',encoding='UTF-8') as file:
    print(file.read()) # 不用再写close了

with open('logo.png','rb') as pic1:
    with open('logo_copy2.png','wb') as pic2:
        pic2.write(pic1.read())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值