-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdircsvtables.py
More file actions
68 lines (31 loc) · 1.34 KB
/
Copy pathdircsvtables.py
File metadata and controls
68 lines (31 loc) · 1.34 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
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
import pathlib
import pymupdf
import csv
print("Convert all tables to csv")
wdir = input("Directory (defaults to CWD): ")
if(wdir == ""):
wdir = pathlib.Path.cwd()
wlkpath = pathlib.Path(wdir)
all_tables = []
for file_path in wlkpath.iterdir():
if(file_path.suffix == ".pdf"):
print(file_path.name)
try:
doc = pymupdf.open(file_path)
for page in doc:
ft = page.find_tables()
if(len(ft.tables)>0):
for tindx,tbl in enumerate(ft):
if(tbl.row_count>1 and tbl.col_count>2):
print("Writing CSV...")
with open(f'{file_path}_{tindx}.csv', 'w', newline='') as csvfile:
tblwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
if(tbl.header.external):
tblwriter.writerow(tbl.header.names)
for row in tbl.extract():
#print(row)
tblwriter.writerow(row)
doc.close()
except Exception as e:
print(f"Error processing {file_path}: {e}")
print("\nTask completed.")