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 str
ing, 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.