python读取文件

读文件

  • 例1:read是按逐个字节读取,会记录当前的指针在哪里,并不是每次都开始读取
# 实例1:读取文本
f = open("demo.txt", "r")
print(f.read(5))
print(f.read(5))
hello
 worl

在这里插入图片描述

  • 例2:读取图片
# 实例2:读取图片
f2 = open("tp.jpeg","r")
print(f2.read())

如果是这样写的话,会得到下面的结果

Traceback (most recent call last):
  File "D:\2022TestTrain\17课练习\读写文件.py", line 17, in <module>
    print(f2.read())
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence

在这里插入图片描述
修改: rb会以二进制的方式来读取

f2 = open("tp.jpeg","rb")
print(f2.read())
  • 例3:
f = open("demo.txt","r")
print(f.readline())
hello world1
  • 例4:
f = open("demo.txt","r")
print(f.readlines())
['hello world1\n', 'hello world2\n', 'hello world3']

写文件

  • 例1:写文件内容时不会校验被写入的文件是否存在
f = open("test01.txt", "w")
f.write("hello world 1\n")
f.write("hello world 2\n") 
f.write("hello world 3")
f.close()

执行脚本后,验证本地文件是否写入成功
在这里插入图片描述
writelines写文件函数,可以轻松实现将其他文件中的数据复制到其他文件中,实现代码如下:

f1 = open("test01.txt", "r")
list1 = f1.readlines()

f2 = open("test02.txt","w")
f2.writelines(list1)

用这种方式处理大文件的时候,任意出现内存溢出

tell()

判断文件指针当前所处的位置,语法是:file.tell()

seek()

将文件指针移动到指定位置,语法是file.seek()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值