Skip to content

Commit b8bca74

Browse files
add default parameter for many read related method, unify path related parameter to filename
1 parent 38be50d commit b8bca74

File tree

1 file changed

+68
-44
lines changed

1 file changed

+68
-44
lines changed

pysenal/io/file.py

Lines changed: 68 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,21 @@
1414
_LINE_BREAK_TUPLE = tuple(_LINE_BREAKS)
1515

1616

17-
def read_lines(filename, encoding=_ENCODING_UTF8, keep_end=False, strip=False, skip_empty=False):
17+
def read_lines(filename, encoding=_ENCODING_UTF8, keep_end=False,
18+
strip=False, skip_empty=False, default=None):
1819
"""
1920
read lines in text file
2021
:param filename: file path
2122
:param encoding: encoding of the file, default is utf-8
2223
:param keep_end: whether keep line break in result lines
2324
:param strip: whether strip every line, default is False
2425
:param skip_empty: whether skip empty line, when strip is False, judge after strip
26+
:param default: returned value when filename is not existed.
27+
If it's None, exception will be raised as usual.
2528
:return: lines
2629
"""
30+
if not os.path.exists(filename) and default is not None:
31+
return default
2732
with open(filename, encoding=encoding) as f:
2833
if strip:
2934
if skip_empty:
@@ -46,17 +51,22 @@ def read_lines(filename, encoding=_ENCODING_UTF8, keep_end=False, strip=False, s
4651
return f.read().splitlines(True)
4752

4853

49-
def read_lines_lazy(src_filename, encoding=_ENCODING_UTF8, keep_end=False, strip=False, skip_empty=False):
54+
def read_lines_lazy(filename, encoding=_ENCODING_UTF8, keep_end=False,
55+
strip=False, skip_empty=False, default=None):
5056
"""
5157
use generator to load files, one line every time
52-
:param src_filename: source file path
58+
:param filename: source file path
5359
:param encoding: file encoding
5460
:param keep_end: whether keep line break in result lines
5561
:param strip: whether strip every line, default is False
5662
:param skip_empty: whether skip empty line, when strip is False, judge after strip
63+
:param default: returned value when filename is not existed.
64+
If it's None, exception will be raised as usual.
5765
:return: lines in file one by one
5866
"""
59-
file = open(src_filename, encoding=encoding)
67+
if not os.path.exists(filename) and default is not None:
68+
return default
69+
file = open(filename, encoding=encoding)
6070
for line in file:
6171
if not keep_end:
6272
line = line.rstrip(_LINE_BREAKS)
@@ -68,13 +78,17 @@ def read_lines_lazy(src_filename, encoding=_ENCODING_UTF8, keep_end=False, strip
6878
file.close()
6979

7080

71-
def read_file(filename, encoding=_ENCODING_UTF8):
81+
def read_file(filename, encoding=_ENCODING_UTF8, default=None):
7282
"""
7383
wrap open function to read text in file
7484
:param filename: file path
7585
:param encoding: encoding of file, default is utf-8
86+
:param default: returned value when filename is not existed.
87+
If it's None, exception will be raised as usual.
7688
:return: text in file
7789
"""
90+
if not os.path.exists(filename) and default is not None:
91+
return default
7892
with open(filename, encoding=encoding) as f:
7993
return f.read()
8094

@@ -123,158 +137,164 @@ def write_lines(filename, lines, encoding=_ENCODING_UTF8, skip_empty=False, stri
123137
f.write('\n'.join(lines) + '\n')
124138

125139

126-
def read_json(src_filename):
140+
def read_json(filename):
127141
"""
128142
read json file
129-
:param src_filename: source file path
143+
:param filename: source file path
130144
:return: loaded object
131145
"""
132-
with open(src_filename, encoding=_ENCODING_UTF8) as f:
146+
with open(filename, encoding=_ENCODING_UTF8) as f:
133147
return json.load(f)
134148

135149

136-
def write_json(dest_filename, data, serialize_method=None):
150+
def write_json(filename, data, serialize_method=None):
137151
"""
138152
dump json data to file, support non-UTF8 string (will not occur UTF8 hexadecimal code).
139-
:param dest_filename: destination file path
153+
:param filename: destination file path
140154
:param data: data to be saved
141155
:param serialize_method: python method to do serialize method
142156
:return: None
143157
"""
144-
with open(dest_filename, 'w', encoding=_ENCODING_UTF8) as f:
158+
with open(filename, 'w', encoding=_ENCODING_UTF8) as f:
145159
if not serialize_method:
146160
json.dump(data, f, ensure_ascii=False)
147161
else:
148162
json.dump(data, f, ensure_ascii=False, default=serialize_method)
149163

150164

151-
def read_jsonline(src_filename, encoding=_ENCODING_UTF8):
165+
def read_jsonline(filename, encoding=_ENCODING_UTF8, default=None):
152166
"""
153167
read jsonl file
154-
:param src_filename: source file path
168+
:param filename: source file path
155169
:param encoding: file encoding
170+
:param default: returned value when filename is not existed.
171+
If it's None, exception will be raised as usual.
156172
:return: object list, an object corresponding a line
157173
"""
158-
file = open(src_filename, encoding=encoding)
174+
if not os.path.exists(filename) and default is not None:
175+
return default
176+
file = open(filename, encoding=encoding)
159177
items = []
160178
for line in file:
161179
items.append(json.loads(line))
162180
file.close()
163181
return items
164182

165183

166-
def read_jsonline_lazy(src_filename, encoding=_ENCODING_UTF8, default=None):
184+
def read_jsonline_lazy(filename, encoding=_ENCODING_UTF8, default=None):
167185
"""
168186
use generator to load jsonl one line every time
169-
:param src_filename: source file path
187+
:param filename: source file path
170188
:param encoding: file encoding
189+
:param default: returned value when filename is not existed.
190+
If it's None, exception will be raised as usual.
171191
:return: json object
172192
"""
173-
if default is not None and not os.path.exists(src_filename):
193+
if not os.path.exists(filename) and default is not None:
174194
return default
175-
file = open(src_filename, encoding=encoding)
195+
file = open(filename, encoding=encoding)
176196
for line in file:
177197
yield json.loads(line)
178198
file.close()
179199

180200

181-
def write_jsonline(dest_filename, items, encoding=_ENCODING_UTF8):
201+
def write_jsonline(filename, items, encoding=_ENCODING_UTF8):
182202
"""
183203
write items to file with json line format
184-
:param dest_filename: destination file path
204+
:param filename: destination file path
185205
:param items: items to be saved line by line
186206
:param encoding: file encoding
187207
:return: None
188208
"""
189209
if isinstance(items, str):
190210
raise TypeError('json object list can\'t be str')
191211

192-
if not dest_filename.endswith('.jsonl'):
212+
if not filename.endswith('.jsonl'):
193213
print('json line filename doesn\'t end with .jsonl')
194214

195215
if not isinstance(items, Iterable):
196216
raise TypeError('items can\'t be iterable')
197-
file = open(dest_filename, 'w', encoding=encoding)
217+
file = open(filename, 'w', encoding=encoding)
198218
for item in items:
199219
file.write(json.dumps(item, ensure_ascii=False) + '\n')
200220
file.close()
201221

202222

203-
def read_ini(src_filename):
223+
def read_ini(filename):
204224
"""
205225
read configs in ini file
206-
:param src_filename: source file path
226+
:param filename: source file path
207227
:return: parsed config data
208228
"""
209229
config = configparser.ConfigParser()
210-
config.read(src_filename)
230+
config.read(filename)
211231
return config
212232

213233

214-
def write_ini(dest_filename, config_data):
234+
def write_ini(filename, config_data):
215235
"""
216236
write config into file
217-
:param dest_filename: destination file
237+
:param filename: destination file
218238
:param config_data: config data
219239
:return: None
220240
"""
221241
config = configparser.ConfigParser()
222242
for key, val in config_data.items():
223243
config[key] = val
224-
with open(dest_filename, 'w') as config_file:
244+
with open(filename, 'w') as config_file:
225245
config.write(config_file)
226246

227247

228-
def append_line(dest_filename, line, encoding=_ENCODING_UTF8):
248+
def append_line(filename, line, encoding=_ENCODING_UTF8):
229249
"""
230250
append single line to file
231-
:param dest_filename: destination file path
251+
:param filename: destination file path
232252
:param line: line string
233253
:param encoding: text encoding to save data
234254
:return: None
235255
"""
236256
if not isinstance(line, str):
237257
raise TypeError('line is not in str type')
238-
with open(dest_filename, 'a', encoding=encoding) as f:
258+
with open(filename, 'a', encoding=encoding) as f:
239259
f.write(line + '\n')
240260

241261

242-
def append_lines(dest_filename, lines, remove_file=False, encoding=_ENCODING_UTF8):
262+
def append_lines(filename, lines, remove_file=False, encoding=_ENCODING_UTF8):
243263
"""
244264
append lines to file
245-
:param dest_filename: destination file path
265+
:param filename: destination file path
246266
:param lines: lines to be saved
247267
:param remove_file: whether remove the destination file before append
248268
:param encoding: text encoding to save data
249269
:return:
250270
"""
251-
if remove_file and os.path.exists(dest_filename):
252-
os.remove(dest_filename)
271+
if remove_file and os.path.exists(filename):
272+
os.remove(filename)
253273
for line in lines:
254-
append_line(dest_filename, line, encoding)
274+
append_line(filename, line, encoding)
255275

256276

257-
def append_jsonline(dest_filename, item, encoding=_ENCODING_UTF8):
277+
def append_jsonline(filename, item, encoding=_ENCODING_UTF8):
258278
"""
259279
append item as a line of json string to file
260-
:param dest_filename: destination file
280+
:param filename: destination file
261281
:param item: item to be saved
262282
:param encoding: file encoding
263283
:return: None
264284
"""
265-
with open(dest_filename, 'a', encoding=encoding) as f:
285+
with open(filename, 'a', encoding=encoding) as f:
266286
f.write(json.dumps(item, ensure_ascii=False) + '\n')
267287

268288

269-
def append_jsonlines(dest_filename, items, encoding=_ENCODING_UTF8):
289+
def append_jsonlines(filename, items, encoding=_ENCODING_UTF8):
270290
"""
271291
append item as some lines of json string to file
272-
:param dest_filename: destination file
292+
:param filename: destination file
273293
:param items: items to be saved
274294
:param encoding: file encoding
275295
:return: None
276296
"""
277-
with open(dest_filename, 'a', encoding=encoding) as f:
297+
with open(filename, 'a', encoding=encoding) as f:
278298
for item in items:
279299
f.write(json.dumps(item, ensure_ascii=False) + '\n')
280300

@@ -400,12 +420,16 @@ def __init__(self, filename, encoding=_ENCODING_UTF8, is_remove=False):
400420
def read(self):
401421
return super().read()
402422

403-
def read_line(self):
423+
def read_line(self, default=None):
424+
if not os.path.exists(self.filename) and default is not None:
425+
return default
404426
self._to_read()
405427
for line in self._file:
406428
yield json.loads(line)
407429

408-
def read_lines(self, skip_empty=False, *args, **kwargs):
430+
def read_lines(self, skip_empty=False, default=None, *args, **kwargs):
431+
if not os.path.exists(self.filename) and default is not None:
432+
return default
409433
self._to_read()
410434
items = []
411435
for line in self._file:

0 commit comments

Comments
 (0)