-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_handler.py
More file actions
35 lines (28 loc) 路 1.24 KB
/
Copy pathfile_handler.py
File metadata and controls
35 lines (28 loc) 路 1.24 KB
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
import csv
from docx import Document
import os
def read_word_document(file_path):
"""Reads content from a Word (.docx) document."""
try:
doc = Document(file_path)
return "\n".join([para.text for para in doc.paragraphs]) or "馃搫 (Word file is empty)"
except Exception as e:
return f"鈿狅笍 Error reading Word document: {e}"
def read_csv_file(file_path):
"""Reads data from a CSV file and formats it as a string."""
try:
with open(file_path, newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
data = [", ".join(row) for row in reader] # Formatting rows as strings
return "\n".join(data) if data else "馃搳 (CSV file is empty)"
except Exception as e:
return f"鈿狅笍 Error reading CSV file: {e}"
def process_file(file_path):
"""Determines file type and reads its content."""
if not os.path.exists(file_path):
return "鈿狅笍 Error: File not found."
if file_path.endswith(".docx"):
return read_word_document(file_path)
elif file_path.endswith(".csv"):
return read_csv_file(file_path)
return "鈿狅笍 Unsupported file type. Please upload a .docx or .csv file."