Repository navigation
Expand file tree
/
Copy pathcreate_open_word.py
More file actions
260 lines (215 loc) · 8.24 KB
/
Copy pathcreate_open_word.py
File metadata and controls
260 lines (215 loc) · 8.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
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
# create_open_word.py
# You must pip install python-docx.
"""
IN THIS CHAPTER
»Automating Microsoft Word and
Microsoft Excel
»Creating, opening, and
watermarking PDFs
160 PART 2 Automating Common Computer Tasks
"""
from datetime import datetime
from docx import Document
from docx.shared import RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from pathlib import Path
import os
import sys
# Here is where you define what you want to put into the document.
def add_content(doc: Document) -> None:
"""
Adds a professionally formatted heading and academic-style introduction
to the provided Document object.
"""
try:
# Heading (Black color, not blue)
heading = doc.add_heading("Badar Rasheed Butt", level=1)
heading.alignment = WD_ALIGN_PARAGRAPH.LEFT
for run in heading.runs:
run.font.color.rgb = RGBColor(0, 0, 0) # Black
# Paragraph 1 – Vision & Identity
p1 = doc.add_paragraph(
"I am Badar Rasheed Butt, a computer scientist driven by a long-term vision to contribute "
"foundational ideas to the field of computing. My ambition is not limited to building software, "
"but to advance the theoretical and applied boundaries of computer science through original "
"research, rigorous thinking, and impactful systems."
)
p1.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
# Paragraph 2 – Research & Direction
p2 = doc.add_paragraph(
"My academic objective is to pursue doctoral-level research and to establish myself among the "
"most influential computer scientists of my generation. I am particularly interested in areas "
"that combine strong theoretical grounding with real-world relevance, including algorithms, "
"artificial intelligence, automation, and large-scale software systems."
)
p2.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
# Paragraph 3 – Practice & Craft
p3 = doc.add_paragraph(
"Alongside research aspirations, I actively develop practical and scalable solutions using "
"Python and modern development tools. I believe that deep theory and strong engineering must "
"coexist, and that meaningful innovation emerges when abstract ideas are tested through "
"implementation."
)
p3.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
# Paragraph 4 – Context of the document
p4 = doc.add_paragraph(
"This document has been generated programmatically using python-docx as a demonstration of "
"how Python can be employed to automate and control Microsoft Word workflows on Windows or macOS, "
"reflecting my broader interest in automation, reproducibility, and computational craftsmanship."
)
p4.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
# Date & Time (current)
now = datetime.now().strftime("%d %B %Y, %I:%M %p")
p5 = doc.add_paragraph(f"Generated on: {now}")
p5.alignment = WD_ALIGN_PARAGRAPH.LEFT
print("Content added to the document.")
except Exception as e:
print(f"Error adding content to document: {e}")
raise
# Create the folder path if it doesn't exist.
def ensure_path_exists(folder_path: str) -> Path:
"""
Ensures the target folder exists; creates it (including parents) if needed.
Args:
folder_path (str): Folder path where the document should live.
Returns:
Path: A resolved Path object pointing to the folder.
Raises:
OSError: Re-raises OS-level directory creation errors after logging.
"""
try:
path = Path(folder_path).resolve()
path.mkdir(parents=True, exist_ok=True)
return path
except OSError as e:
print(f"Error creating directory {folder_path}: {e}")
raise
# Ensure the filename has a .docx extension.
def validate_file_name(file_name: str) -> str:
"""
Ensures the provided filename ends with .docx (case-insensitive check).
Args:
file_name (str): The intended file name.
Returns:
str: The validated filename (with .docx appended if missing).
"""
if not file_name.lower().endswith(".docx"):
file_name += ".docx"
return file_name
# Open an existing .docx file or create a new one.
def open_or_create_docx(folder_path: Path, file_name: str) -> Document:
"""
Opens an existing .docx document if present; otherwise creates a new one.
Args:
folder_path (Path): The folder Path where the document is located/created.
file_name (str): The .docx file name.
Returns:
Document: The python-docx Document object (opened or newly created).
Raises:
Exception: Re-raises any exception after logging.
"""
file_path = folder_path / file_name
# Returns the Document object.
try:
if file_path.exists():
print(f"Opening existing document: {file_path}")
return Document(file_path)
else:
print(f"Creating new document: {file_path}")
doc = Document()
doc.save(file_path) # Initialize the file
return doc
except Exception as e:
print(f"Error opening or creating document {file_path}: {e}")
raise
# Save the document to the specified path.
def save_document(doc: Document, file_path: Path) -> None:
"""
Saves the given Document object to the provided file path.
Args:
doc (Document): The document to save.
file_path (Path): The full path (including filename) to save to.
Returns:
None
Raises:
Exception: Re-raises any exception after logging.
"""
try:
doc.save(file_path)
print(f"Document saved successfully: {file_path}")
except Exception as e:
print(f"Error saving document {file_path}: {e}")
raise
# Open the file in the default application on Windows or macOS.
def open_file(file_path: Path) -> None:
"""
Opens the given file path in the OS default application.
- Windows: uses os.startfile
- macOS: uses `open` via os.system
- Other OS: prints a message (no auto-open support)
Args:
file_path (Path): The full path to the file to open.
Returns:
None
Raises:
Exception: Re-raises any exception after logging.
"""
try:
if sys.platform.startswith("win"):
os.startfile(str(file_path))
elif sys.platform.startswith("darwin"):
# Use os.system instead of subprocess to open the file on macOS
os.system(f'open "{file_path}"')
else:
print(
"Unsupported OS for auto opening the file. Please open manually:",
file_path,
)
except Exception as e:
print(f"Error opening the file {file_path}: {e}")
raise
# Uses all the preceding functions to create or open a Word document and
# add content
def process_document(folder_path: str, file_name: str) -> None:
"""
End-to-end workflow:
1) Ensure folder exists
2) Validate filename extension
3) Open or create the .docx
4) Add content
5) Save
6) Open in default app (when supported)
Args:
folder_path (str): Target folder for the document.
file_name (str): Target document file name.
Returns:
None
Raises:
Exception: Re-raises any exception after logging.
"""
try:
path = ensure_path_exists(folder_path)
file_name = validate_file_name(file_name)
file_path = path / file_name
doc = open_or_create_docx(path, file_name)
add_content(doc)
save_document(doc, file_path)
open_file(file_path)
except Exception as e:
print(f"Failed to process document: {e}")
raise
# Specify your path and filename here.
def main():
"""
Entry point:
- Sets the folder path (Windows by default; macOS path provided as comment)
- Sets the output file name
- Runs the document processing pipeline
"""
# Windows path
folder_path = r"C:\Users\Badar-Butt\Documents"
file_name = "badar_document.docx"
# Create or open the document and add content.
process_document(folder_path, file_name)
if __name__ == "__main__":
main()