Skip to content
This repository has been archived by the owner on Aug 22, 2024. It is now read-only.

ENH TextGrid.read(): accept file-like object #37

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions textgrid/textgrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

import re
import codecs
import contextlib
import os.path
import logging

Expand Down Expand Up @@ -101,6 +102,26 @@ def detectEncoding(f):
return encoding


@contextlib.contextmanager
def as_file(obj, encoding):
"""
Accept file-object or path-like object for reading TextGrid
"""
if hasattr(obj, 'readline'):
do_close = False
file_obj = obj
else:
do_close = True
if encoding is None:
encoding = detectEncoding(obj)
file_obj = codecs.open(obj, 'r', encoding=encoding)
try:
yield file_obj
finally:
if do_close:
file_obj.close()


class Point(object):
"""
Represents a point in time with an associated textual mark, as stored
Expand Down Expand Up @@ -692,11 +713,10 @@ def pop(self, i=None):
def read(self, f, round_digits=DEFAULT_TEXTGRID_PRECISION, encoding=None):
"""
Read the tiers contained in the Praat-formatted TextGrid file
indicated by string f. Times are rounded to the specified precision.
indicated by path or file-like object f.
Times are rounded to the specified precision.
"""
if encoding is None:
encoding = detectEncoding(f)
with codecs.open(f, 'r', encoding=encoding) as source:
with as_file(f, encoding) as source:
file_type, short = parse_header(source)
if file_type != 'TextGrid':
raise TextGridError('The file could not be parsed as a TextGrid as it is lacking a proper header.')
Expand Down