On Mon, Jan 21, 2013 at 7:56 AM, Lie Ryan <lie.1...@gmail.com> wrote:
> On 22/01/13 04:02, kwakukwat...@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) >> + f.readline(), >> > > 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()
-- http://mail.python.org/mailman/listinfo/python-list