簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM