-
Notifications
You must be signed in to change notification settings - Fork 0
/
filemanager.py
549 lines (449 loc) · 17.3 KB
/
filemanager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
import os
class FileManager:
""" A class to facilitate path management and file operations for common file-related tasks.
Methods can be split into the following groups:
- Path Validation (e.g., is_file, is_directory)
- Path Manipulation (e.g., path_join, get_file_extension)
- File Operations (e.g., create_file, delete_file)
- File Content Management (e.g., read_content, write_content)
- Directory Operations (e.g., create_directory, delete_directory)
Author
------
Sean O'Hara
Attributes
----------
path: ``None`` (default) or str
Optional attribute, defines the global path used for all methods.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'`` or ``'C:\\Users\\johndoe\\Documents'``
Methods
-------
Path Validation
is_file(path)
Checks if a path points to a file.
is_directory(path)
Checks if a path points to a directory.
is_valid_path(path)
Checks if path is a file, directory, parent directory, or includes file extension.
path_exists(path)
Checks if a path pointing to a file or directory exists.
Path Manipulation
path_join(components)
Joins multiple path components into a single path.
change_directory(path)
Changes the current working directory.
get_current_directory()
Returns the current working directory path.
get_parent_directory(path)
Returns the parent directory of a path (if any).
get_base_name(path)
Returns the base name of a path (if any).
get_file_extension(path)
Returns the file extension of a path (if any).
File Operations
create_file(path):
Creates a new file.
rename_file(new_path, path):
Renames an existing file.
delete_file(path):
Deletes an existing file.
File Content Management
read_content(path):
Reads the file content.
write_content(content, path):
Writes the provided content to a file.
append_content(content, path):
Appends the provided content to a file.
read_line(path):
Reads single line of a file.
read_all_lines(path):
Reads all lines of a file.
write_lines(lines, path):
Writes the provided lines to a file.
clear_file_content(path):
Clears the file content.
Directory Operations
list_directory_contents(path):
Lists the contents of a directory.
create_directory(path):
Creates a new directory.
rename_directory(new_path, path):
Renames an existing directory.
delete_directory(path):
Deletes an existing directory.
"""
def __init__(self, path=None):
if path is None:
self._path = self.get_current_directory()
else:
self.path = path
@property
def path(self):
return self._path
@path.setter
def path(self, value):
if isinstance(value, str) and self.is_valid_path(value):
self._path = value
else:
raise ValueError('Invalid path attribute')
# --- Path Validation Methods ---
def is_file(self, path=None):
""" Checks if a path points to a file.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
Returns
-------
bool
``True`` if file exists, otherwise ``False``.
"""
path = self._path if path is None else path
self._validate_params(path, str, 'validate file')
return os.path.isfile(path)
def is_directory(self, path=None):
""" Checks if a path points to a directory.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the directory.
ex: ``'C:\\Users\\johndoe\\Documents'``
Returns
-------
bool
``True`` if directory exists, otherwise ``False``.
"""
path = self._path if path is None else path
self._validate_params(path, str, 'validate directory')
return os.path.isdir(path)
def is_valid_path(self, path=None):
""" Checks if path is a file, directory, parent directory, or includes file extension.
Returns
-------
bool
``True`` if path is valid, otherwise ``False``.
"""
is_file = self.is_file(path)
is_dir = self.is_directory(path)
is_par = True if self.get_parent_directory(path) else False
has_ext = True if self.get_file_extension(path) else False
return is_file or is_dir or has_ext or is_par
def path_exists(self, path=None):
""" Checks if a path pointing to a file or directory exists.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the file or directory.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'`` or ``'C:\\Users\\johndoe\\Documents'``
Returns
-------
bool
``True`` if path exists, otherwise ``False``.
"""
path = self._path if path is None else path
self._validate_params(path, str, 'validate path')
return os.path.exists(path)
# --- Path Manipulation Methods ---
def path_join(self, *components):
""" Joins multiple path components into a single path.
Parameters
----------
*components: positional arguments
Any number of path components as strings.
ex: ``'C:\\Users\\johndoe\\Documents'``, ``'file.txt'``
Returns
-------
str
The joined single path.
"""
for component in components:
self._validate_params(component, str, 'join path')
return os.path.join(*components)
def change_directory(self, path=None):
""" Changes the current working directory.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the directory.
ex: ``'C:\\Users\\johndoe'``
"""
path = self._path if path is None else path
self._validate_params(path, str, 'change directory')
os.chdir(path)
def get_current_directory(self):
""" Returns the current working directory path.
Returns
-------
str
The current working directory path.
"""
return os.getcwd()
def get_parent_directory(self, path=None):
""" Returns the parent directory of a path (if any).
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the directory.
ex: ``'C:\\Users\\johndoe\\Documents'``
Returns
-------
str
The parent directory path (if any).
"""
path = self._path if path is None else path
self._validate_params(path, str, 'get parent directory')
return os.path.dirname(path)
def get_base_name(self, path=None):
""" Returns the base name of a path (if any).
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the file/directory.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
Returns
-------
str
The base name of a path (if any).
"""
path = self._path if path is None else path
self._validate_params(path, str, 'get base name')
return os.path.basename(path)
def get_file_extension(self, path=None):
""" Returns the file extension of a path (if any).
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
Returns
-------
str
The file extension of a path (if any).
"""
path = self._path if path is None else path
self._validate_params(path, str, 'get file extension')
return os.path.splitext(path)[1]
# --- File Operations Methods ---
def create_file(self, path=None):
""" Creates a new file.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
"""
path = self._path if path is None else path
self._validate_params(path, str, 'create file')
self._op_handler(path, 'write')
def rename_file(self, new_path, path=None):
""" Renames an existing file.
Parameters
----------
new_path: str
The path of the new file.
ex: ``'C:\\Users\\johndoe\\Documents\\file2.txt'``
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file1.txt'``
"""
path = self._path if path is None else path
self._validate_params((new_path, path), (str, str), 'rename file')
self._op_handler(path, 'rename', new_path)
def delete_file(self, path=None):
""" Deletes an existing file.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
"""
path = self._path if path is None else path
self._validate_params(path, str, 'delete file')
self._op_handler(path, 'remove')
# --- File Content Management Methods ---
def read_content(self, path=None):
""" Reads the file content.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
Returns
-------
str
The file content.
"""
path = self._path if path is None else path
self._validate_params(path, str, 'read content')
return self._op_handler(path)
def write_content(self, content, path=None):
""" Writes the provided content to a file.
Parameters
----------
content: str
The content to write.
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
"""
path = self._path if path is None else path
self._validate_params((content, path), (str, str), 'write content')
self._op_handler(path, 'write', content)
def append_content(self, content, path=None):
""" Appends the provided content to a file.
Parameters
----------
content: str
The content to append.
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
"""
path = self._path if path is None else path
self._validate_params((content, path), (str, str), 'append content')
self._op_handler(path, 'append', content)
def read_line(self, path=None):
""" Reads single line of a file.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
Returns
-------
str
The line of the file.
"""
path = self._path if path is None else path
self._validate_params(path, str, 'read line')
return self._op_handler(path, 'readline')
def read_all_lines(self, path=None):
""" Reads all lines of a file.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
Returns
-------
list
The lines of the file.
"""
path = self._path if path is None else path
self._validate_params(path, str, 'read lines')
return self._op_handler(path, 'readlines')
def write_lines(self, lines, path=None):
""" Writes the provided lines to a file.
Parameters
----------
lines: list
The lines to write.
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
"""
path = self._path if path is None else path
self._validate_params((lines, path), (list, str), 'write lines')
self._op_handler(path, 'writelines', lines)
def clear_file_content(self, path=None):
""" Clears the file content.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the file.
ex: ``'C:\\Users\\johndoe\\Documents\\file.txt'``
"""
path = self._path if path is None else path
self._validate_params(path, str, 'clear content')
self._op_handler(path, 'write')
# --- Directory Operations Methods ---
def list_directory_contents(self, path=None):
""" Lists the contents of a directory.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the directory.
ex: ``'C:\\Users\\johndoe\\Documents'``
"""
path = self._path if path is None else path
self._validate_params(path, str, 'list directory')
return self._op_handler(path, 'listdir')
def create_directory(self, path=None):
""" Creates a new directory.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the directory.
ex: ``'C:\\Users\\johndoe\\Documents'``
"""
path = self._path if path is None else path
self._validate_params(path, str, 'create directory')
self._op_handler(path, 'mkdir')
def rename_directory(self, new_path, path=None):
""" Renames an existing directory.
Parameters
----------
new_path: str
The path of the new directory.
ex: ``'C:\\Users\\johndoe\\Documents\\folder2'``
path: ``None`` (default) or str
Optional parameter, the path of the directory.
ex: ``'C:\\Users\\johndoe\\Documents\\folder1'``
"""
path = self._path if path is None else path
self._validate_params((new_path, path), (str, str), 'rename directory')
self._op_handler(path, 'rename', new_path)
def delete_directory(self, path=None):
""" Deletes an existing directory.
Parameters
----------
path: ``None`` (default) or str
Optional parameter, the path of the directory.
ex: ``'C:\\Users\\johndoe\\Documents'``
"""
path = self._path if path is None else path
self._validate_params(path, str, 'delete directory')
self._op_handler(path, 'rmdir')
def _validate_params(self, params, types, op):
if not isinstance(params, (list, tuple, dict, set)):
params = (params,)
if not isinstance(types, (list, tuple, dict, set)):
types = (types,)
for param, type_ in zip(params, types):
if not (param and isinstance(param, type_)):
raise ValueError(f'Unable to {op}: invalid parameter')
def _op_handler(self, path, op='read', data=''):
try:
if op == 'listdir':
return os.listdir(path)
elif op == 'mkdir':
os.mkdir(path)
elif op == 'rename':
os.rename(path, data)
elif op in ('remove', 'rmdir'):
os.remove(path) if op == 'remove' else os.rmdir(path)
else:
mode = op[0]
with open(path, mode) as f:
if op == 'read':
return f.read()
elif op in ('write', 'append'):
f.write(data)
elif op == 'readline':
return f.readline()
elif op == 'readlines':
return f.readlines()
elif op == 'writelines':
f.writelines(data)
except FileNotFoundError:
raise FileNotFoundError('No such file or directory') from None
except FileExistsError:
raise FileExistsError('File already exists') from None
except PermissionError:
raise PermissionError('Insufficient file permissions') from None
except OSError:
raise OSError('OS error during file operation') from None
except UnicodeDecodeError:
raise ValueError('Unable to read file content') from None
except Exception as e:
raise ValueError(e) from None