IO流文件读写

#P1 打开文件、读文件、关闭文件的典型方法

try:
    f=open('D:/test.txt','r')
    print(f.read())

finally:
    if f:
        f.close()


#P2 推荐的简洁写法,不必显示的关闭文件描述符
#open返回的对象在python中称作file-like 对象,可以是字节流、网络流、自定义流等
with open('D:/test.txt','r') as f:
    #按行读取
    for line in f.readlines():
        print(line.strip())

#P3 直接读取二级制的图片、视频文件

# with open('D:/banner.jpg','rb') as f2:
#     for line in f2.readlines():
#         print(line.strip())


#P4 可以指定编码读取相应的数据,还可以忽略非法编码

with open('D:/test.txt','r',encoding='gbk',errors='ignore') as f3:
    for line in f3.readlines():
        print(line.strip())

#P5 写文件的流程和读文件是一样的 代开文件、写入内容、关闭文件

# 'r'    open for reading (default)
# 'w'    open for writing, truncating the file first
# 'x'    open for exclusive creation, failing if the file already exists
# 'a'    open for writing, appending to the end of the file if it exists
# 'b'    binary mode
# 't'    text mode (default)
# '+'    open a disk file for updating (reading and writing)
# 'U'    universal newlines mode (deprecated)
with open('D:/test12.txt','a+') as f4:
    for line in f4.readlines():
        print(line.strip())
    f4.write('a new line2!')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值