代码之家  ›  专栏  ›  技术社区  ›  Xantium

只读取文件的第一个值

  •  0
  • Xantium  · 技术社区  · 6 年前

    背景: 我有一个大文件,我想从中读取前几个值。我真的不想读取整个文件,部分原因是我对它没有进一步的使用,这样它就不会使用不必要的内存,并且执行起来更快(因为它不需要读取这个巨大的文件)。


    来自 documentation 我正在使用:

    测试.txt

    Greetings World :)
    

    测试.py:

    with open('test.txt', buffering=3) as file:
        a = file.read()
    print(a)
    

    它不仅部分读取了我的文件。

    有没有方法只读取文件的一部分?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Xantium    6 年前

    What is the use of buffering in python's built-in open() function? buffering a.read()

    with open('test.txt') as file:
        a = file.read(3) 
    print(a)
    

    Gre

    documentation

    a.seek() seek() function?

        2
  •  2
  •   Xantium    6 年前

    file.read()

    file.read(size)

    file.readlines() list(file) for line in file:

    file.readline() \n

    check here