Skip to content

Instantly share code, notes, and snippets.

@informationsea
Created January 17, 2012 13:08
Show Gist options
  • Save informationsea/1626575 to your computer and use it in GitHub Desktop.
Save informationsea/1626575 to your computer and use it in GitHub Desktop.
Read Tab-Separeted file by python
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