Educating yourself does not mean that you were stupid in the first place; it means that you are intelligent enough to know that there is plenty left to 'learn'. -Melanie Joy

Friday 21 December 2012

Best way to open files in Python

December 21, 2012 Posted by Dinesh No comments
C like syntax is as follows,

f = open("file", 'r')
line = f.readline( )
print line
close(f)

some one may forget to close f. this leads to leak, which is considerable in large scale programs. in order to avoid that we  can make use of 'with' or 'for' keywords.


with open("file", 'r') as f:
        line = f.readline()
        print line
or

for line in open("file", 'r'):
       print line


in these scenarios, file will get closed when f is out of scope.

0 comments:

Post a Comment