• python读取文件的前几行


    文件内容rolling.txt:

    There's a fire starting in my heart
    我怒火中烧
    Reaching a fever pitch and it's bringing me out the dark
    熊熊烈焰带我走出黑暗
    Finally, I can see you crystal clear
    最终 我将你看得一清二楚
    Go ahead and sell me out and I'll lay your ship bare
    去吧 出卖我 我会让你一无全部
    See how I'll leave with every piece of you
    看我怎么离你而去 带走你的一切
    Don't underestimate the things that I will do
    不要低估我将来的所作所为
    There's a fire starting in my heart
    我怒火中烧
    Reaching a fever pitch and it's bring me out the dark
    熊熊烈焰带我走出黑暗
    The scars of your love remind me of us
    你的爱情伤痕让我想起了我们曾经的甜蜜
    They keep me thinking that we almost had it all
    它们总在提醒我 我们几乎拥有了一切
    The scars of your love, they leave me breathless
    你的爱情伤痕 让我窒息
    I can't help feeling
    我不禁心生感触
    We could have had it all
    我们本该拥有一切
    (You're gonna wish you never had met me)
    (你会祈祷 要是从未遇见我该有多好)
    Rolling in the deep
    内心深处爱恨交织
    (Tears are gonna fall, rolling in the deep)
    (眼泪快要掉下来,内心深处爱恨交织)
    You had my heart inside your hand
    你俘虏了我的芳心
    (You're gonna wish you never had met me)
    (你会祈祷 要是从未遇见我该有多好)
    And you played it to the beat
    但是你玩弄它 伴着每一次心跳
    (Tears are gonna fall, rolling in the deep)
    (眼泪快要掉下来,内心深处爱恨交织)
    Baby, I have no story to be told
    宝贝 我没有故事可讲
    But I've heard one on you and I'm gonna make your head burn
    但是我听说了一件有关你的事情 我会让你焦头烂额
    Think of me in the depths of your despair
    在绝望的深渊中想起我
    Making a home down there as mine sure won't be shared
    就在那里安家吧 因为我的家园绝对没你的份
    The scars of your love remind me of us
    你的爱情伤痕让我想起了我们曾经的甜蜜
    (You're gonna wish you never had met me)
    (你会祈祷 要是从未遇见我该有多好)
    They keep me thinking that we almost had it all
    它们总在提醒我 我们几乎拥有了一切
    

     一行行的读取文件前5行

    第一种方法:

     for i in range(5):
         print(f.readline().strip())
    

     第二种方法:

    line_nu = 0#计数器
    for line in f:#一行行的把数据从硬盘加载到内存里读出来
        if line_nu<5:#读取前五行
            print(line.strip())
            line_nu += 1
        else:
            break
    

     最简单的两种方法。

  • 相关阅读:
    Java正则表达式学习 贪婪 勉强 侵占
    HTML meta
    URLConnection类
    Sql Server 查看所有存储过程或视图的位置及内容
    创建你的第一个游戏Pong——挑战:改进您的Pong游戏
    解决锚点在IE8中失效
    辅助类——掌握内容管道
    辅助类——随机函数(RandomHelper)辅助类
    创建你的第一个游戏Pong——疑难解答
    辅助类——概览
  • 原文地址:https://www.cnblogs.com/zhangyux/p/6002040.html
Copyright © 2020-2023  润新知