gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:41:43 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

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

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 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.


编辑:

回答诺亚的评论:

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

关于python - 你如何在 Python 中读取文本文件的特定行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7523001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com