![](/img/trans.png)
[英]Readlines method in Python skipping the first line in a file after heading
[英]Skipping over the first line of a text file using readlines() in python
我是一名初学者程序员,试图在 python 中构建密码管理器。 我一直在尝试编写一个 function,它允许您通过将文本文件打印到控制台来查看它们的内容。 `
def view():
with open("passwords.txt", "r") as p:
for line in p.readlines():
if line == p.readlines()[0]:
pass
data = line.rstrip()
user, passw = data.split("|")
print("User: ", user, "| password: ", passw)
对于上下文,我的文本文件的第一行是一个标题,所以我想跳过第一行。 我认为 readlines() 方法返回文本文件中所有字符串的列表,但是当我尝试通过索引访问第一行时,出现“IndexError: list index out of range”错误。 跳过第一行或文本文件的任何行的正确方法是什么? 谢谢,这是我第一次在这里发帖
在遍历剩余的行之前,您可以使用p.readline()
或next(readline)
跳过一行。 这将读取一行,然后将其丢弃。
foo.txt
:
this is the end
hold your breath
and count to ten
代码:
with open('foo.txt', 'r') as f:
f.readline()
for line in f:
print(line, end='')
# hold your breath
# and count to ten
您可以使用 readlines()[n:] 跳过前 n 行。
with open('passwords.txt', 'r') as p:
lines = p.readlines()[1:] # skipping first line
for line in lines:
data = line.rstrip()
user, passw = data.split("|")
print("User: ", user, "| password: ", passw)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.