Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

line

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.

like image 788
Noah R Avatar asked Sep 23 '11 00:09

Noah R


4 Answers

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
like image 142
chown Avatar answered Dec 24 '22 06:12

chown


You can use Python's inbuilt module linecache

  import linecache
  line = linecache.getline(filepath,linenumber)
like image 25
user1302884 Avatar answered Dec 24 '22 05:12

user1302884


load_profile.readline(1)

specifically says to cap at 1 byte. it doesn't mean 1 line. Try

read_it = load_profile.readline()
like image 32
Foo Bah Avatar answered Dec 24 '22 07:12

Foo Bah


def readline_number_x(file,x):
    for index,line in enumerate(iter(file)):
        if index+1 == x: return line

    return None

f = open('filename')
x = 3
line_number_x = readline_number_x(f,x) #This will return the third line
like image 22
Julien Grenier Avatar answered Dec 24 '22 07:12

Julien Grenier