【问题标题】:How to read a specific part of a file如何读取文件的特定部分
【发布时间】:2013-02-14 17:04:43
【问题描述】:

我有一个大文件,我将只发布其中的一小部分:

World population in thousands
Source: United Nations, DEMOBASE

Country/ISO country code/UN Code/Population 1950/Population 2012
----------------------------------------------------------------
Afghanistan/AF/4/8151/33397
Albania/AL/8/1215/3227
Algeria/DZ/12/8753/36486
American Samoa/AS/16/19/71
Andorra/AD/20/6/88

我的问题是如何阅读前 5 行,即国家信息开始之前的信息。

我试过类似的东西:

file=open("wordpop.txt","r")
for i in range[0:5]:
    rows = file.read()
print(rows)

【问题讨论】:

    标签: python file for-loop


    【解决方案1】:

    range() 是一个函数,而不是一个列表。 range(5) 会工作得更好,但你只是读取文件 5 次(读取空结果四次)。

    使用readline() 读取文件中的一个行,并使用列表推导轻松将这些行放入列表中:

    with open("wordpop.txt","r") as infile:
        rows = [infile.readline() for _ in range(5)]
    print(rows)
    

    【讨论】:

      【解决方案2】:

      试试:

      for line in file.readlines()[:5]:
          print line
      

      【讨论】:

      • 是的,但我认为只要文件不是绝对巨大,它看起来更干净/更清晰
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多