Search code examples
pythonline

How do you read a specific line of a text file in Python?


I'm having trouble reading an entire specific line of a text file using Python. I currently have this:

load_profile = open('users/file.txt', "r")
read_it = load_profile.readline(1)
print read_it

Of course this will just read one byte of the first line, which is not what I want. I also tried Google but didn't find anything.


Solution

  • What are the conditions of this line? Is it at a certain index? Does it contain a certain string? Does it match a regex?

    This code will match a single line from the file based on a string:

    load_profile = open('users/file.txt', "r")
    read_it = load_profile.read()
    myLine = ""
    for line in read_it.splitlines():
        if line == "This is the line I am looking for":
            myLine = line
            break
    print myLine
    

    And this will give you the first line of the file (there are several other ways to do this as well):

    load_profile = open('users/file.txt', "r")
    read_it = load_profile.read().splitlines()[0]
    print read_it
    

    Or:

    load_profile = open('users/file.txt', "r")
    read_it = load_profile.readline()
    print read_it
    

    Check out Python File Objects Docs

    file.readline([size])

    Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. When size is not 0, an empty string is returned only when EOF is encountered immediately.

    Note Unlike stdio‘s fgets(), the returned string contains null characters ('\0') if they occurred in the input.

    file.readlines([sizehint])

    Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently.


    Edit:

    Answer to your comment Noah:

    load_profile = open('users/file.txt', "r")
    read_it = load_profile.read()
    myLines = []
    for line in read_it.splitlines():
        # if line.startswith("Start of line..."):
        # if line.endswith("...line End."):
        # if line.find("SUBSTRING") > -1:
        if line == "This is the line I am looking for":
            myLines.append(line)
    print myLines