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))

Recommended Answers

All 6 Replies

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

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

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?

You need to let folks know more about the module Pdf and where you got it from. Google doesn't bring it up.

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.