reading from sys.stdin

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Fri Apr 13 06:09:46 EDT 2007


In <1176457624.259636.197030 at p77g2000hsh.googlegroups.com>, 7stud wrote:

> On Apr 13, 3:36 am, "7stud" <bbxx789_0... at yahoo.com> wrote:
>>
>> > It is if the file is smaller than the buffer size.
>>
>> How is that relevant?
>>
> 
> If I put 100 lines of text in a file with each line having 50
> characters, and I run this code:
> 
> import sys
> 
> lst = []
> for line in open("aaa.txt"):
>     print "an iteration"
>     lst.append(line)
>     break
> 
> print lst
> 
> 
> The output is:
> 
> $ python test1.py
> 
> an iteration
> ['helleo haljdfladj ahdflasdjf ds hdljfalsdjfdsljfds \n']
> 
> It seems clear to me that the whole file wasn't first read into a
> buffer before the code started processing the data.

How is that clear to you?  Why do you think the file was not loaded
completely into a buffer and only the first line from this buffer ends up
in `lst`?

Let's try this:

def main():
    test_file = open('test.txt', 'w')
    for i in xrange(100):
        test_file.write('%d %s\n' % (i, 'x' * 50))
    test_file.close()
    
    test_file = open('test.txt', 'r')
    for line in test_file:
        print line
        break
    print '>%s<' % test_file.read(75)
    test_file.close()

Output:
0 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

><

You see the read after the loop doesn't read anything because the file
content is in the buffer of the iterator.  If the test file has more
lines, I tested it with 1000, the output looks like this:

0 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

>xx
151 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
152 xxxxxxxxxxxxx<

Ciao,
	Marc 'BlackJack' Rintsch




More information about the Python-list mailing list