Skip to content

Instantly share code, notes, and snippets.

@arunenigma
Created March 11, 2013 09:49
Show Gist options
  • Select an option

  • Save arunenigma/5133128 to your computer and use it in GitHub Desktop.

Select an option

Save arunenigma/5133128 to your computer and use it in GitHub Desktop.
Pro Python File Handling!
import logging
def count_lines(filename):
"""
Count the number of lines in a file. If the file can't be opened it should be treated as an empty file
:param filename:
"""
f = None
try:
f = open(filename, 'r')
lines = f.readlines()
except TypeError as e:
# invalid file
logging.error(e)
return 0
except EnvironmentError as e:
# error reading file
logging.error(e.args[1])
return 0
except UnicodeDecodeError as e:
# contents of file in unknown encoding
logging.error(e)
return 0
else:
return len(lines)
finally:
if f:
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment