搜索
您的当前位置:首页正文

python读取文件的前几行

来源:哗拓教育
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

最简单的两种⽅法。

因篇幅问题不能全部显示,请点此查看更多更全内容

Top