[Tutor] A Really Quick Question

Todd Maynard python-tutor at toddmaynard.com
Sat Oct 22 16:54:13 CEST 2005


Hi Steve,

Here is the python documentation.  Hopefully it is a *little* clearer....

http://docs.python.org/lib/bltin-file-objects.html

*** readlines ***

readlines(  [sizehint])
 Read until EOF using readline() and return a list containing the lines thus 
read. If the optional sizehint argument is present, instead of reading up to 
EOF, whole lines totalling approximately sizehint bytes (possibly after 
rounding up to an internal buffer size) are read. Objects implementing a 
file-like interface may choose to ignore sizehint if it cannot be 
implemented, or cannot be implemented efficiently.

*** read ***
read(  [size])
 Read at most size bytes from the file (less if the read hits EOF before 
obtaining size bytes). If the size argument is negative or omitted, read all 
data until EOF is reached. The bytes are returned as a string object. An 
empty string is returned when EOF is encountered immediately. (For certain 
files, like ttys, it makes sense to continue reading after an EOF is hit.) 
Note that this method may call the underlying C function fread() more than 
once in an effort to acquire as close to size bytes as possible. Also note 
that when in non-blocking mode, less data than what was requested may be 
returned, even if no size parameter was given.

***********************

If you want to only read X bytes at a time then read would be more 
appropriate.

Have fun learning,

--Todd


On Saturday 22 October 2005 10:18, Steve Haley wrote:
> Folks,
>
>
>
> I am running Python 2.1 which ships with ArcView 9.1.  I am going through
> the 2.1 tutorial and came across readlines().  Simply put it doesn't seem
> to be behaving as the tutorial describes.  Specifically, I created a small
> text file as shown below:
>
>
>
> f=open("c:/python21/sfh_modules/test.txt", "w")
>
> f.write("This is the second line\n")
>
> f.write("This is the second line\n")
>
> f.close()  # then closed and reopened in read mode
>
> f=open("c:/python21/sfh_modules/test.txt", "r")
>
> f.readlines(2)  # Here's my problem
>
> ['This is the first line\n', 'This is the second line\n']  # please note
> this output
>
>
>
> The tutorial seems to be telling me that 'f.readlines(2) should read out 2
> bytes plus what is needed to complete the current line.  Instead, it is
> reading out the entire file no matter what I enter as a parameter.  I know
> I am going to feel really dumb when I hear the explanation but please
> remember I'm new to this.
>
>
>
> Thanks very much,
>
> Steve


More information about the Tutor mailing list