Created
January 17, 2012 13:08
-
-
Save informationsea/1626575 to your computer and use it in GitHub Desktop.
Read Tab-Separeted file by python
This file contains 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
def suggest_type_from_str(string): | |
""" | |
Arguments: | |
- `string`: | |
""" | |
try: | |
return int(string) | |
except: | |
try: | |
return float(string) | |
except: | |
return str(string) | |
class TabSeparatedFile(object): | |
""" | |
""" | |
def __init__(self, filepath): | |
""" | |
Arguments: | |
- `filepath`: | |
""" | |
self._filepath = filepath | |
self._file = None | |
def __enter__(self): | |
""" | |
Arguments: | |
- `self`: | |
""" | |
return self | |
def __del__(self): | |
""" | |
Arguments: | |
- `self`: | |
""" | |
self.close() | |
def __exit__(self, exc_type, exc_value, traceback): | |
""" | |
Arguments: | |
- `self`: | |
""" | |
self.close() | |
def __iter__(self): | |
""" | |
Arguments: | |
- `self`: | |
""" | |
if self._file == None: | |
self._file = open(self._filepath, 'r') | |
for line in self._file: | |
yield map(suggest_type_from_str, line[:-1].split('\t')) | |
def close(self): | |
""" | |
Arguments: | |
- `self`: | |
""" | |
if self._file: | |
self._file.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment