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

发布于 12-05 23:26 字数 213 浏览 1 评论 0原文

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

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

日记撕了你也走了2024-12-12 23:26:42

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

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

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([大小])

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

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

file.readlines([sizehint])

使用readline()读取直到EOF并返回
包含如此读取的行的列表。如果可选尺寸提示
存在参数,而不是读取到 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

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
香草可樂2024-12-12 23:26:42

您可以使用Python的内置模块linecache

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

You can use Python's inbuilt module linecache

  import linecache
  line = linecache.getline(filepath,linenumber)
难如初2024-12-12 23:26:42
load_profile.readline(1)

特别指出上限为 1 字节。它并不意味着 1 行。尝试

read_it = load_profile.readline()
load_profile.readline(1)

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

read_it = load_profile.readline()
错々过的事2024-12-12 23:26:42
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
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
ま柒月2024-12-12 23:26:42

我通过从文本中创建一个列表并询问列表中的“第 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.

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文