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

Noa*_*h R 4 python line

我在使用Python读取文本文件的整个特定行时遇到问题.我目前有这个:

load_profile = open('users/file.txt', "r")
read_it = load_profile.readline(1)
print read_it
Run Code Online (Sandbox Code Playgroud)

当然这只会读取第一行的一个字节,这不是我想要的.我也试过谷歌,但没有找到任何东西.

cho*_*own 14

这条线的条件是什么?它在某个指数?它是否包含某个字符串?它与正则表达式匹配吗?

此代码将根据字符串匹配文件中的单行:

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
Run Code Online (Sandbox Code Playgroud)

这将为您提供文件的第一行(还有其他几种方法可以执行此操作):

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

要么:

load_profile = open('users/file.txt', "r")
read_it = load_profile.readline()
print read_it
Run Code Online (Sandbox Code Playgroud)

查看Python文件对象文档

file.readline([大小])

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

注意与stdio的fgets()不同,返回的字符串如果在输入中出现,则包含空字符('\ 0').

file.readlines([sizehint])

使用readline()读取EOF并返回包含如此读取的行的列表.如果存在可选的sizehint参数,则不会读取到EOF,而是读取总计近似sizehint字节的整行(可能在四舍五入到内部缓冲区大小之后).如果无法实现或无法有效实现,则实现类文件接口的对象可以选择忽略sizehint.


编辑:

回答你的评论诺亚:

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
Run Code Online (Sandbox Code Playgroud)