简体   繁体   English

在 python 中使用 readlines() 跳过文本文件的第一行

[英]Skipping over the first line of a text file using readlines() in python

I'm a beginner programmer trying to build a password manager in python.我是一名初学者程序员,试图在 python 中构建密码管理器。 I've been trying to write an function that allows you to view the contents of the text file by printing them to the console.我一直在尝试编写一个 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)

for context the very first line of my text file is a heading so I want to skip over the first line.对于上下文,我的文本文件的第一行是一个标题,所以我想跳过第一行。 I thought that the readlines() method returns a list of all strings in the text file, however when I try accessing the first line through indexing I get an 'IndexError: list index out of range' error.我认为 readlines() 方法返回文本文件中所有字符串的列表,但是当我尝试通过索引访问第一行时,出现“IndexError: list index out of range”错误。 What is the correct approach of skipping the first line, or any line for that matter of a text file?跳过第一行或文本文件的任何行的正确方法是什么? thank you this is my first time posting on here谢谢,这是我第一次在这里发帖

You can use p.readline() or next(readline) to skip a line, before you loop over the remaining lines.在遍历剩余的行之前,您可以使用p.readline()next(readline)跳过一行。 This will read a line, and then just throw it away.这将读取一行,然后将其丢弃。

foo.txt : foo.txt

this is the end
hold your breath
and count to ten

Code:代码:

with open('foo.txt', 'r') as f:
    f.readline()
    for line in f:
        print(line, end='')

# hold your breath
# and count to ten

You can use readlines()[n:] to skip the first n line(s).您可以使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM