如何在 Python 中读取文本文件的特定行?
我在使用 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 技术交流群。
发布评论
评论(5)
ま柒月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.
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
这条线路的条件是什么?是否达到某个指数?它包含特定的字符串吗?它与正则表达式匹配吗?
此代码将根据字符串匹配文件中的一行:
这将为您提供文件的第一行(还有其他几种方法可以做到这一点):
或者:
查看 Python 文件对象文档
编辑:
回答你的评论诺亚:
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:
And this will give you the first line of the file (there are several other ways to do this as well):
Or:
Check out Python File Objects Docs
Edit:
Answer to your comment Noah: