I'm a beginner programmer trying to build a password manager in 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. `
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. 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. This will read a line, and then just throw it away.
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).
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.