Created
March 11, 2013 09:49
-
-
Save arunenigma/5133128 to your computer and use it in GitHub Desktop.
Pro Python File Handling!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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