# why not?

Josh Benner sjbenner at gmail.com
Tue Jan 22 08:04:14 CET 2013

On Mon, Jan 21, 2013 at 7:56 AM, Lie Ryan <lie.1296 at gmail.com> wrote:

> On 22/01/13 04:02, kwakukwatiah at gmail.com wrote:
>
>> f = open(r'c:\text\somefile.txt')
>> for i in range(3):
>>         print str(i) + ': ' + f.readline(),
>> please with the print str(i) + ‘: ‘ + f.readline(), why not print str(i)
>>
>
> Try running both code. What do you see? What's the difference? When do you
> think you might want one or the other?
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>

There is nothing 'wrong' with either print statement.  The why or why not,
depends on the requirements of who or what intends to 'consume' the output.
In other words, what problem does this code solve?  Think about which
print statement produces the best output for that problem.

It is also always a good idea to close the file object when you are done
with it.  Consider executing file operations inside a 'with' block.

with open(r'c:\text\somefile.txt') as f:
for i in range(3):
print str(i) + ': ' + f.readline()

The above code can be generalized further for use with text files that
contain a variable number of lines.

with open(r'c:\text\somefile.txt') as f:
for index, line in enumerate( f ):
print str( index ) + ': ' + f.readline()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130121/732b83b0/attachment.html>