[Tutor] readline

Mike McTernan livingmike at gmail.com
Thu Aug 1 00:01:27 CEST 2013


Thanks everyone.

For some reason I thought that readline counted the \n at the end of
each line and stopped at each one. Clearly, I was mistaken!

mike

On Wed, Jul 31, 2013 at 2:05 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 31/07/13 21:12, Mike McTernan wrote:
>>
>> I am having problems with the readline command in Python 2.7.
>
>
>> script, zodiac = argv
>> prediction = open(zodiac, "r")
>
> This code is very fragile, you should check that zodiac is actually being
> set by the user and ideally that it is a real file before using it.
> Alternatively use a try/except block to catch any error. The latter is
> probably the most Pythonic approach.
>
>
>       if "Leo" in star_sign:
>           print prediction.readline(5)
>
>
>> instead of printing the line 5 it prints the first 5 letters on line 1.
>
>
> What made you think it would read line 5? The help clearly says:
>
> readline(...)
>     readline([size]) -> next line from the file, as a string.
>
>     Retain newline.  A non-negative size argument limits the maximum
>     number of bytes to return (an incomplete line may be returned then).
>     Return an empty string at EOF.
> (END)
>
> So the '5' limits the number of *bytes* read not the lines.
>
> The program is working exactly as you should expect.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



-- 

http://mikejmct.blogspot.com/


More information about the Tutor mailing list