python - Read only the first line of a file?


Translate

How would you get only the first line of a file as a string with Python?


All Answers
  • Translate

    Use the .readline() method (Python 2 docs, Python 3 docs):

    with open('myfile.txt') as f:
        first_line = f.readline()
    

    Some notes:

    1. As noted in the docs, unless it is the only line in the file, the string returned from f.readline() will contain a trailing newline. You may wish to use f.readline().strip() instead to remove the newline.
    2. The with statement automatically closes the file again when the block ends.
    3. The with statement only works in Python 2.5 and up, and in Python 2.5 you need to use from __future__ import with_statement
    4. In Python 3 you should specify the file encoding for the file you open. Read more...

  • Translate
    infile = open('filename.txt', 'r')
    firstLine = infile.readline()
    

  • Translate
    fline=open("myfile").readline().rstrip()
    

  • Translate

    This should do it:

    f = open('myfile.txt')
    first = f.readline()
    

  • Translate

    To go back to the beginning of an open file and then return the first line, do this:

    my_file.seek(0)
    first_line = my_file.readline()
    

  • Translate
    first_line = next(open(filename))
    

  • Translate

    Lots of other answers here, but to answer precisely the question you asked (before @MarkAmery went and edited the original question and changed the meaning):

    >>> f = open('myfile.txt')
    >>> data = f.read()
    >>> # I'm assuming you had the above before asking the question
    >>> first_line = data.split('\n', 1)[0]
    

    In other words, if you've already read in the file (as you said), and have a big block of data in memory, then to get the first line from it efficiently, do a split() on the newline character, once only, and take the first element from the resulting list.

    Note that this does not include the \n character at the end of the line, but I'm assuming you don't want it anyway (and a single-line file may not even have one). Also note that although it's pretty short and quick, it does make a copy of the data, so for a really large blob of memory you may not consider it "efficient". As always, it depends...


  • Translate

    Solution1:

    with open('input_file.txt') as input_file:
        lines=input_file.readlines()
        for line_no, line in enumerate(lines):
            if line_no == 0:
                print(line)
                break
    
    • lines contains all the lines from the input_file.txt
    • line_nowill give the line number from the files
    • if the line_no is 0, the first line will be printed as the index starts from 0
    • Similarly, if you want second line, you can write if line_no==1

    Solution 2:

    with open('input_file.txt') as input_file:
        lines=input_file.readlines()
        first_line=lines[0]
        print(first_line)
    
    • lines[0] is the first line.
    • Similarly, lines[1] is the second line

    Solution 3:

    Print first N lines. Replace N with any number. If you want first line, then N=1

    from itertools import islice
    
    with open('my_file.txt','r') as my_file:
        head = list(islice(my_file, N))
        print(head)
    

    This is the equivalent code of unix command head

    Solution 4:

    with open('input.txt', 'r') as fin:
        head, tail = fin.read().split('\n', 1)
        print(head)
        #print(tail)
    

  • Translate
    f1 = open("input1.txt", "r")
    print(f1.readline())