Can't print a specific line from text file

匆匆过客 提交于 2019-12-24 13:42:54

问题


So I currently have this code to read an accounts.txt file that looks like this:

username1:password1
username2:password2
username3:password3

I then have this (thanks to a member here) read the accounts.txt file and split it at the username and password so I can later print it. When I try to print line 1 with the username and password separate with this code:

with open('accounts.txt') as f:

    credentials = [x.strip().split(':') for x in f.readlines()]



for username,password in credentials:

    print username[0]
    print password[0]

It prints out this:

j
t
a
2
a
3

(These are the three lines I have in the text file, properly split, however it's printing all the lines and only the first letter of each line.)

I've tried a few different methods with no luck. Anyone have an idea on what to do?

Thank you for all your help. It's really appreciated. This is my second day programming and I apologize for such a simple question.


回答1:


username and password are strings. When you do this to a string, you get the first character in the string:

username[0]

Don't do that. Just print username.

Some further explanation. credentials is a list of lists of strings. It looks like this when you print it out:

[['username1', 'password1'], ['username2', 'password2'], ['username3', 'password3']]

To get one username/password pair, you could do this: print credentials[0]. The result would be this:

['username1', 'password1']

Or if you did print credentials[1], this:

['username2', 'password2']

You can also do a thing called "unpacking," which is what your for loop does. You can do it outside a for loop too:

username, password = credentials[0]
print username, password

The result would be

username1 password1

And again, if you take a string like 'username1' and take a single element of it like so:

username[0]

You get a single letter, u.




回答2:


First, I'd like to say if this is your second day programming, then you're off to a good start by using the with statement and list comprehensions already!

As the other people already pointed out, since you are using [] indexing with a variable that contains a string, it treats the str as if it were an array, so you get the character at the index you specify.

I thought I'd point out a couple of things:

1) you don't need to use f.readline() to iterate over the file since the file object f is an iterable object (it has the __iter__ method defined which you can check with getattr(f, '__iter__'). So you can do this:

with open('accounts.txt') as f:
    for l in f:
        try:
            (username, password) = l.strip().split(':')
            print username
            print password
        except ValueError:
            # ignore ValueError when encountering line that can't be
            # split (such as blank lines).
            pass

2) You also mentioned you were "curious if there's a way to print only the first line of the file? Or in that case the second, third, etc. by choice?"

The islice(iterable[, start], stop[, step]) function from the itertools package works great for that, for example, to get just the 2nd & 3rd lines (remember indexes start at 0!!!):

from itertools import islice
start = 1; stop = 3
with open('accounts.txt') as f:
    for l in islice(f, start, stop):
        try:
            (username, password) = l.strip().split(':')
            print username
            print password
        except ValueError:
            # ignore ValueError when encountering line that can't be
            # split (such as blank lines).
            pass

Or to get every other line:

from itertools import islice
start = 0; stop = None; step = 2
with open('accounts.txt') as f:
    for l in islice(f, start, stop, step):
        try:
            (username, password) = l.strip().split(':')
            print username
            print password
        except ValueError:
            # ignore ValueError when encountering line that can't be
            # split (such as blank lines).
            pass

Spend time learning itertools (and its recipes!!!); it will simplify your code.



来源:https://stackoverflow.com/questions/9073699/cant-print-a-specific-line-from-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!