Skip to content

Commit 749a99b

Browse files
committed
Cleanup challenge 17.2
1 parent 72cdb50 commit 749a99b

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

ch17-graphical-user-interfaces/2-challenge.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@
77
from PyPDF2 import PdfFileReader, PdfFileWriter
88

99
# let the user choose an input file
10-
input_file_name = gui.fileopenbox("", "Select a PDF to trim...", "*.pdf")
11-
if input_file_name is None: # exit on "Cancel"
10+
input_file_path = gui.fileopenbox("", "Select a PDF to trim...", "*.pdf")
11+
if input_file_path is None: # exit on "Cancel"
1212
exit()
1313

1414
# get the page length of the input file
15-
input_file = PdfFileReader(open(input_file_name, "rb"))
15+
input_file = PdfFileReader(input_file_path)
1616
total_pages = input_file.getNumPages()
1717

1818
# let the user choose a beginning page
@@ -62,15 +62,15 @@
6262
exit()
6363

6464
# let the user choose an output file name
65-
output_file_name = gui.filesavebox("", "Save the trimmed PDF as...", "*.pdf")
66-
while input_file_name == output_file_name: # cannot use same file as input
65+
output_file_path = gui.filesavebox("", "Save the trimmed PDF as...", "*.pdf")
66+
while input_file_path == output_file_path: # cannot use same file as input
6767
gui.msgbox(
6868
"Cannot overwrite original file!", "Please choose another file..."
6969
)
70-
output_file_name = gui.filesavebox(
70+
output_file_path = gui.filesavebox(
7171
"", "Save the trimmed PDF as...", "*.pdf"
7272
)
73-
if output_file_name is None:
73+
if output_file_path is None:
7474
exit() # exit on "Cancel"
7575

7676
# read in file, write new file with trimmed page range and save the new file
@@ -79,6 +79,7 @@
7979
for page_num in range(int(page_start) - 1, int(page_end)):
8080
page = input_file.getPage(page_num)
8181
output_PDF.addPage(page)
82-
output_file = open(output_file_name, "wb")
83-
output_PDF.write(output_file)
84-
output_file.close()
82+
83+
with open(output_file_path, "wb") as output_file:
84+
output_PDF.write(output_file)
85+

0 commit comments

Comments
 (0)