python文件的读取操作

打开文件

f=open("F:/python/helloworld/测试.txt","r",encoding="UTF-8")

读取文件

print(f"读取10个字节的结果{f.read(10)}")
print(f"读取全部字节的结果{f.read()}")
lines=f.readlines()
print(f"{lines}")

读取文件一行

f.readline()
line1=f.readline()
line2=f.readline()
line3=f.readline()
print(f"第一行{line1}")
print(f"第二行{line2}")
print(f"第三行{line3}")

循环读取文件

for line in f:
    print(f"{line}")

文件关闭

f.close()

with open的使用

文件读取完成后,要使用文件对象.close()方法关闭文件对象,否则文件会被一直占用,使用with open可以自动关闭

with open("F:/python/helloworld/测试.txt","r",encoding="UTF-8") as f:
    for line in f:
        print(f"{line}")

两个使用案例

f=open("F:/python/helloworld/测试.txt","r",encoding="UTF-8")
conten=f.read()
count=conten.count("三体")
print(f"ci{count}")


count=0
for line in f:
    line=line.strip() #去除开头和结尾的空格和换行符
    words=line.split(" ")
 
    for word in words:
        if word == "三体":
            count+=1
        print(count )

总结

1.操作文件需要open函数打开文件得到文件对象
2.文件对象读取方法:
read()
readline()
readlines()
for line in 文件对象
3.文件读取完成后,要使用文件对象.close()方法关闭文件对象,否则文件会被一直占用

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值