首页 > 编程语言 > 详细

python-文件操作2(读写文件的详细操作)

时间:2019-11-27 10:18:05      阅读:86      评论:0      收藏:0      [点我收藏+]

python-文件操作2(读写文件的详细操作)

1、读取文件的前6行数据

f = open ("my-hert2","r")  #encoding="utf-8"
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())

另一种写法:

f = open ("my-hert2","r")  #encoding="utf-8"
for i in range(6):
print(f.readline())

打印结果如下-----

遥远的东方有一条龙,

它的名字叫中国

遥远的东方有一群人,

他们都是中国人

古老的东方有条河

它的名字叫黄河

 

2、打印所有文件内容,但十行不打印

第一种写法

f = open ("my-heart","r")
for index,line in enumerate(f.readlines()):  #读小文件可以,如果大文件就慢了
    if  index==9:
        print("------分割线")
        continue
    print(line.strip())
count=0

第二种写法 高效的循环

count=0
f = open("my-heart","r")
for line in f:
    if count ==9:
        print(-----分割线----)
        count+=1
        continue
    print(line.strip()) #取消空行,和空格
    count +=1

 文件打开光标的位置

f=open(my-heart,r)
print(f.tell())    #返回光标的位置
print(f.read(5))   # 默认是读全部,可以只读部份,
print(f.tell())

----------------
打印结果
0
Every
5

 

python-文件操作2(读写文件的详细操作)

原文:https://www.cnblogs.com/kezi/p/11939462.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!