[Tutor] grave confusion

Alan Gauld alan.gauld at btinternet.com
Mon Oct 6 12:48:19 CEST 2014


On 06/10/14 03:19, Clayton Kirkwood wrote:
> Here's my problem; my code snippet reads a file(presumably an _io.readline,
> I'll question this later), with the file.readline().

Nope, it reads a line from a file.
That's quite a different thing.

> The output shows
> individual characters being read and printed out followed by the "here"
> being printed. Also, see below.

Because a for loop iterates over a string character by character
And because the print 'here' is inside the loop. I'm not sure
if thats deliberate or not.


> for line_in in file.readline():
>       print( line_in )
>       print("here")
>       continue

You don't need the continue since the loop will continue from
the end of the block automatically. Thats what loops do.

> Why the individual characters and not the full line?

Because you are iterating over the line which is a
collection of characters. So the for loop breaks it
down to each character.

> Also, it is very unclear to me which readline I am using.

We can't be certain since you only show a snippet which does not include 
you opening the file. But based on the output you are
using a file readline and  in Python 3 a text file is an
instance of class _io.TextIOWrapper
But you don't need to know that, its just a "file-like object".

> I have imported os. I am using pycharm IDE and supposedly it
 > will show me where readline is coming from ... it brings up three
> readlines which are place holders. It doesn't bring up the os.readline.

I don't think there is an os.readline.
You don't need the IDE to tell you where things are coming from
just look at your code. What is file? Where does it come from?
Thats the readline() you are using.

If you type help(file) it will give you the documentation of
file including its superclasses if any.

> getting really tired of trying to figure out which function is being used!

Mostly you don't need to.
Use them. If in doubt use help().
In this case help(file.readline)

> So, what is happening that I am missing?

Mostly the fact that readline() reads a line() not the entire file.
That would be readlines()

But nowadays you rarely need readlines(() either. You should just 
iterate over the file. So your code should be:

for line in file:
    print(line)
    print('help')

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list