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

     
  • 相关阅读:
    627. Swap Salary
    176. Second Highest Salary
    596. Classes More Than 5 Students
    183. Customers Who Never Order
    181. Employees Earning More Than Their Managers
    182. Duplicate Emails
    175. Combine Two Tables
    620. Not Boring Movies
    595. Big Countries
    HDU 6034 Balala Power! (贪心+坑题)
  • 原文地址:https://www.cnblogs.com/kezi/p/11939462.html
Copyright © 2011-2022 走看看