-1

So, I'm a new programmer python is my first language. I'm trying to create a program to randomly open a pdf from a directory and read/display one page. Anyway thats what I got so far. I'm just wondering if theres a more efficient way to write this. Any advice?

import os, random, Pdf
from Pdf import PdfFileReader, PageObject 

b = random.choice(os.listdir("/home/illman/reading/books/PDF")) 

Pdf_toRead = PdfFileReader(open(b, 'r'))
page_one = pdf_toRead.getPage(random.randrange(0, 10000))

Edited by wolf_one

6
Contributors
6
Replies
78
Views
3 Years
Discussion Span
Last Post by chriswelborn
0

It looks quite efficient to me... I don't know if you can compact it much more if any.

0

it is good well done i will encorage you to keep on working hard and trying new stuff that is the only way to learn. and also try hard to answer other peoples question you find out that you will be learning more

0

Only looks little strange that all documents have 10001 pages. Hope page zero also exists, normally page numbering starts from 1, not zero, I do not know details of the Pdf module. Wouldn't there be any method to find the number of pages in document?

0

I used pyPdf for the module. Yeah that last line is giving me some trouble. How would I go about checking the number of pages in the PDF and randomly selecting one? Thanks for the feedback guys I appreciate it.

Edited by wolf_one

0

To get last page number and randomly select one:

last_page = Pdf_toRead.getNumPages() - 1
page_one = pdf_toRead.getPage(random.randint(0, last_page))

Also, it seems they do start at 0 like a normal list/tuple/array. Hince the 'getNumPages() - 1'.

I haven't used the pyPdf module, but IDLE and Control + Space works wonders for exploring modules/objects.

Edited by chriswelborn: added IDLE reference...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.