【问题标题】:How i can read the first 10 lines and the last 10 line from filei in python我如何从 python 中的文件中读取前 10 行和最后 10 行
【发布时间】:2020-05-12 16:05:55
【问题描述】:

我有一个文件,它包含数千个值,所以我不会只读取前 10 个和最后 10 个值

所以我使用了 v.readline() 还有 v.read() 但它没有给我解决方案

【问题讨论】:

  • 您必须澄清“文件”的含义。您指的是包含数据行的 txt 文件吗?还是 csv、xls、PDF 文件?或者这是一个存储在 python 脚本中的长变量?
  • 这是一个 txt.file 我正在尝试从中读取

标签: python python-3.x list loops file


【解决方案1】:

使用 next 函数遍历文件。

with open("file") as f:
    lines = [next(f) for x in range(10)]

【讨论】:

    【解决方案2】:

    简单打印:

    res=[]
    with open('filename.txt') as inf:
        for count, line in enumerate(inf, 1):
            res.append(str(count))
    for r in range(10):
        print(res[r])
    for r in range(count-10,count):
        print(res[r])
    

    或者,这会将输出保存为变量“结果”:

    res=[]
    result=''
    with open('filename.txt') as inf:
        for count, line in enumerate(inf, 1):
            res.append(str(count))
    for r in range(10):
        result = result + '\n' + res[r]
    for r in range(count-10,count):
        result = result + '\n' + res[r]
    print(result)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多