Harshit2N commited on
Update file_handler.py
Browse filesAdded error/exception handling and better file handling
data/contexts/file_handler.py
CHANGED
|
@@ -1,17 +1,36 @@
|
|
| 1 |
-
import os
|
| 2 |
-
|
| 3 |
def read_files(file_list):
|
| 4 |
contents = []
|
| 5 |
for filename in file_list:
|
| 6 |
-
f =
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
return contents
|
| 10 |
|
| 11 |
def write_output(data, filename):
|
| 12 |
-
|
|
|
|
|
|
|
| 13 |
f.write(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
def append_to_file(filename, data):
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
def read_files(file_list):
|
| 2 |
contents = []
|
| 3 |
for filename in file_list:
|
| 4 |
+
f = None
|
| 5 |
+
try:
|
| 6 |
+
f = open(filename, 'r', encoding='utf-8')
|
| 7 |
+
contents.append(f.read())
|
| 8 |
+
except Exception as e:
|
| 9 |
+
print(f"Error reading {filename}: {e}")
|
| 10 |
+
contents.append(None)
|
| 11 |
+
finally:
|
| 12 |
+
if f:
|
| 13 |
+
f.close()
|
| 14 |
return contents
|
| 15 |
|
| 16 |
def write_output(data, filename):
|
| 17 |
+
f = None
|
| 18 |
+
try:
|
| 19 |
+
f = open(filename, 'w', encoding='utf-8')
|
| 20 |
f.write(data)
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f"Error writing to {filename}: {e}")
|
| 23 |
+
finally:
|
| 24 |
+
if f:
|
| 25 |
+
f.close()
|
| 26 |
|
| 27 |
def append_to_file(filename, data):
|
| 28 |
+
f = None
|
| 29 |
+
try:
|
| 30 |
+
f = open(filename, 'a', encoding='utf-8')
|
| 31 |
+
f.write(data)
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"Error appending to {filename}: {e}")
|
| 34 |
+
finally:
|
| 35 |
+
if f:
|
| 36 |
+
f.close()
|