zoukankan      html  css  js  c++  java
  • python-文件操作2(读写文件的详细操作)

    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())
    print(f.seek(0)) #查找的意思,光标就回到原点,然后再readline,打印首行
    print(f.readline())
    ---------------- 打印结果 

    0
    Every
    5
    0
    Every night in my dreams

     
  • 相关阅读:
    实现一个简单的Form授权 How to: Implement Simple Forms Authentication
    寄存器寻址方式
    HDU2094 产生冠军
    HDU1060 Leftmost Digit 数论
    HDU1496 Equations [hash]
    HDU1298 T9 字典树 DFS
    HDU1051 Wooden Sticks
    HDU1800 Flying to the Mars
    HDU1285 确定比赛名次 拓扑排序
    HDU1716 排列2 组合数
  • 原文地址:https://www.cnblogs.com/kezi/p/11939462.html
Copyright © 2011-2022 走看看