-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_handling.py
56 lines (47 loc) · 1.88 KB
/
file_handling.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
import os
import glob
# Error messages
FILE_TO_READ_NOT_FOUND = "File not found."
READ_FILE_ERROR = "An error occured whild reading the file. "
FILE_TO_WRITE_NOT_FOUND_ERROR="Path to File not found."
FILE_TO_WRITE_IO_ERROR="Input/Output error while writing file."
FILE_TO_WRITE_UNEXPECTED_ERROR="An unexpected error occured while writing the file."
def find_all_files_with_specific_ending(base_directory: str, file_ending: str="*"):
"""
retuns a list of all files in the given base_directory with the file ending
parameter base_directory: the directory to search in
parameter file_ending: the file ending to filter for. E.g. "py" or nothing/None for all file endings
"""
sep = os.sep
search_pattern = os.path.join(base_directory, f'**{sep}*.{file_ending}')
files = glob.glob(search_pattern, recursive=True)
return files
def read_file_content(filePath) -> str:
"""
Returns the content of a file or a string with an error
"""
try:
with open(filePath, 'r', encoding='utf-8') as file_to_read:
content = file_to_read.read()
return content
except FileNotFoundError:
return f"{FILE_TO_READ_NOT_FOUND} - Path: {filePath}"
except Exception as e:
return f"{READ_FILE_ERROR} - Path: {filePath} - Exception: {e}"
def save_content_in_file(path, content):
"""
Saves the content in the file with the given path
If there is an exception the program quits after printing the error
"""
try:
with open(path, 'w', encoding='utf-8') as file:
file.write(content)
except FileNotFoundError:
print(f"{FILE_TO_WRITE_NOT_FOUND_ERROR} - Path: {path}")
exit(1)
except IOError:
print(f"{FILE_TO_WRITE_IO_ERROR} - Path: {path}")
exit(1)
except Exception as e:
print(FILE_TO_WRITE_UNEXPECTED_ERROR + f"Path: {path} - Exception: {e}")
exit(1)