106
106
"""
107
107
# [[[end]]]
108
108
109
- import codecs
109
+ from io import IOBase
110
110
from pathlib import Path
111
111
from typing import Iterable , Union , Optional , TextIO
112
112
113
113
114
- from .node import parse_lines , OrgEnv , OrgNode # todo basenode??
115
- from .utils .py3compat import basestring
114
+ from .node import parse_lines , OrgEnv , OrgNode # todo basenode??
116
115
117
116
__author__ = 'Takafumi Arakaki, Dmitrii Gerasimov'
118
117
__license__ = 'BSD License'
119
118
__all__ = ["load" , "loads" , "loadi" ]
120
119
121
120
122
- def load (path : Union [str , Path , TextIO ], env : Optional [OrgEnv ]= None ) -> OrgNode :
121
+ def load (path : Union [str , Path , TextIO ], env : Optional [OrgEnv ] = None ) -> OrgNode :
123
122
"""
124
123
Load org-mode document from a file.
125
124
@@ -129,17 +128,24 @@ def load(path: Union[str, Path, TextIO], env: Optional[OrgEnv]=None) -> OrgNode:
129
128
:rtype: :class:`orgparse.node.OrgRootNode`
130
129
131
130
"""
132
- orgfile : TextIO
133
- if isinstance (path , (str , Path )):
134
- # Use 'with' to close the file inside this function.
135
- with codecs .open (str (path ), encoding = 'utf8' ) as orgfile :
136
- lines = (l .rstrip ('\n ' ) for l in orgfile .readlines ())
137
- filename = str (path )
138
- else :
139
- orgfile = path
140
- lines = (l .rstrip ('\n ' ) for l in orgfile .readlines ())
141
- filename = path .name if hasattr (path , 'name' ) else '<file-like>'
142
- return loadi (lines , filename = filename , env = env )
131
+ # Make sure it is a Path object.
132
+ if isinstance (path , str ):
133
+ path = Path (path )
134
+
135
+ # if it is a Path
136
+ if isinstance (path , Path ):
137
+ # open that Path
138
+ with path .open ('r' , encoding = 'utf8' ) as orgfile :
139
+ # try again loading
140
+ return load (orgfile , env )
141
+
142
+ # We assume it is a file-like object (e.g. io.StringIO)
143
+ all_lines = (line .rstrip ('\n ' ) for line in path )
144
+
145
+ # get the filename
146
+ filename = path .name if hasattr (path , 'name' ) else '<file-like>'
147
+
148
+ return loadi (all_lines , filename = filename , env = env )
143
149
144
150
145
151
def loads (string : str , filename : str = '<string>' , env : Optional [OrgEnv ]= None ) -> OrgNode :
0 commit comments