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

谁都会走 提交于 2020-05-10 18:50:17

问题


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.


回答1:


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



回答2:


You can use Python's inbuilt module linecache

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



回答3:


load_profile.readline(1)

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

read_it = load_profile.readline()



回答4:


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


来源:https://stackoverflow.com/questions/7523001/how-do-you-read-a-specific-line-of-a-text-file-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!