Tuesday, July 1, 2014

Python Script for Opening a Random PDF in a Given Directory

I decided to try learning Python, so I came up with a script of nominal utility. It's probably quite ugly, but it works.

It opens a random PDF from a directory full of PDFs that I've accumulated over the past year or so of articles I've been meaning to read. At the end, it prompts the user to save or delete the file. It's quite cathartic.

If you have a similar problem, I hope this helps clean up your life a bit. Red text is where you fill in the blanks. If you're using Windows, make sure to use forward slashes for the path (e.g. 'D:/users/something/something')


import os, sys, time
from random import randint
# Clear the command window
clear = lambda: os.system('cls')
clear()
# Set the path with all of the PDF files
path = '[directory with all of the files]'
# Create a list of all of the PDF files
pdf_files = [f for f in os.listdir(path) if f.endswith('.pdf')]
# Clean up the names by removing spaces
for pdf_file in pdf_files:
os.rename(os.path.join(path, pdf_file), os.path.join(path, pdf_file.replace(' ', '_')))
len_pdf_files = len(pdf_files)
# Generate a random number
rand_int = randint(0,len_pdf_files)
# Get the name of a random PDF file
file_name_str = str(pdf_files[rand_int])
file_loc_str = path + '/' + file_name_str
# Generate a string to be used to open the file
pdf_cmd_str = "start " + file_loc_str # Windows uses "start"
# Open the file
os.system(pdf_cmd_str)
# Prompt the user to delete the file
delete_file = input("Delete file? Y or N: ")
if delete_file == "Y":
os.remove(file_loc_str)
print (file_name_str + " deleted! Good work!")
# Give the user a few seconds to read the statement
time.sleep(3)
sys.exit(0)
else:
# Chastise them for being a hoarder, while enabling them
print ("Fine then, but next time, delete it!")
time.sleep(3)
sys.exit(0)

No comments: