开发者

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 = op开发者_运维技巧en('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.


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


You can use Python's inbuilt module linecache

  import linecache
  line = linecache.getline(filepath,linenumber)


load_profile.readline(1)

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

read_it = load_profile.readline()


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


I managed to read an specific line by making a list out of the text, and asking what is the "n-th" element of the list.

with open('filename') as xp:
    texto=xp.read() #This makes a string out of the text
    listexto=texto.splitlines() #This makes a list out of the string, making
                                #every element of the list equal to each line
                                #in the string.
    print(listexto[8]) #This prints the eight element of the list.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜