如何在Python中读取文本文件的特定行?

8

我需要使用Python读取文本文件中的一整行,但是目前遇到了困难。我现在有以下代码:

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

当然,这只会读取第一行的一个字节,这不是我想要的。我也试过谷歌,但没有找到任何有用信息。
5个回答

15

这行代码是基于字符串匹配文件中的一行:

这一行的条件是什么?它在特定索引上吗?它是否包含特定字符串?它是否与正则表达式匹配?

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

这将给你文件的第一行(还有其他几种方法可以实现此功能):

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

或者:

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

请查看Python文件对象文档

file.readline([size])

从文件中读取整行。字符串末尾会保留一个换行符(但在文件以不完整的行结尾时,可能会缺少该换行符)。[6]如果存在size参数且为非负数,则它是最大字节数(包括换行符)并且可能返回不完整的行。当size不为0时,只有在立即遇到EOF时才返回空字符串。

注意:与stdio的fgets()函数不同,返回的字符串包含输入中出现的空字符('\0')。

file.readlines([sizehint])

使用readline()读取直到EOF,并返回一个包含已读取行的列表。如果可选的sizehint参数存在,则不是读取直到EOF,而是读取总大小约为sizehint字节的整行(可能会被舍入到内部缓冲区大小)。实现文件类似接口的对象可以选择忽略sizehint,如果无法实现或无法有效地实现则可以忽略。


编辑:

回复你的评论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

没问题,Noah!很高兴能帮忙。 - chown
如果我有一些具有相同文本的行,该怎么办? - Noah R
我会将您的三个例子的顺序颠倒,无论如何都要给您点赞,谢谢您提供的详细信息。 - agf

4
您可以使用Python内置的linecache模块。
  import linecache
  line = linecache.getline(filepath,linenumber)

2
load_profile.readline(1)

具体指定为上限1字节。这并不意味着1行。请尝试。

read_it = load_profile.readline()

1
这将只读取第一行。我需要读取一个特定的不是第一行的行。 - Noah R
@NoahRainey,你的陈述是"当然,这只会读取第一行的一个字节,这不是我想要的。"。而它只读取第一行的一个字节的原因是readline(n)表示读取下一行,最多读取n个字符。你应该调用readline() n-1次,然后捕获readline的结果。 - Foo Bah

1
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

0

我通过将文本转换为列表,并询问列表的第n个元素,成功读取了特定行。

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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接