I decided to get a little fancy with the "random PDF" script from my last post.
I modified the random selection element to be weighted based on age. I decided to start simple by simply dividing file age (in days) by 10 (I'll try using the log next), rounding up (using math.ceil) and randomly selecting from a new array (called "weighted_files") which gives more weight to older files. Basically: I want it to be more likely that an older file is opened rather than a newer file. My reading model has now shifted to a FIFO scheme.
Here it is, with a few comments.
#! /usr/bin/python
import time, os, math, sys, shutil
from random import randint
clear = lambda: os.system('cls')
clear()
path = '[DIRECTORY WITH PDF FILES IN IT]'
pdf_files = [f for f in os.listdir(path) if f.endswith('.pdf')]
len_pdf_files = len(pdf_files)
if len_pdf_files == 0:
print ("No PDF files found!")
time.sleep(3)
sys.exit(0)
pdf_ages = []
for pdf_file in pdf_files:
os.rename(os.path.join(path, pdf_file), os.path.join(path, pdf_file.replace(' ', '_')))
file_loc = path + '/' + pdf_file
file_age_sec = time.time() - os.path.getmtime(file_loc)
file_age_days = file_age_sec/60/60/24
file_age_days_round = math.floor(file_age_days)
pdf_ages.append(file_age_days_round)
# Build an array for use in weighted random selection
weighted_files = []
weighting_factor = 10 # arbitrary
for index, pdf_age in enumerate(pdf_ages):
weight = math.ceil(pdf_age/weighting_factor)
# Adds the index number (from pdf_ages, which should match pdf_files) in proportion to the weight
for i in range(0,weight):
weighted_files.append(index)
len_weighted_files = len(weighted_files)
rand_int = randint(0,len_weighted_files-1)
pdf_files_index = weighted_files[rand_int]
file_name_str = str(pdf_files[pdf_files_index])
file_loc_str = path + '/' + file_name_str
pdf_cmd_str = "start " + file_loc_str
os.system(pdf_cmd_str)
valid_command = 0
while valid_command == 0 :
delete_file = input("Delete file? Y or N: ")
if (delete_file == "Y" or delete_file == "y"):
os.remove(file_loc_str)
print (file_name_str + " has been deleted! Good work!")
new_num_pdfs = len_pdf_files - 1
new_num_pdfs_str = str(new_num_pdfs)
print ("There are now ",new_num_pdfs_str," PDFs remaining.")
time.sleep(3)
valid_command = 1
sys.exit(0)
elif (delete_file == "N" or delete_file == "n"):
print ("Fine then, but next time, delete it!")
dest_folder_loc_str = 'D:/Users/a27m8mt/Documents/Things_To_Read/Hold_for_later/'
shutil.move(file_loc_str,dest_folder_loc_str)
print (file_name_str + " has been moved to the holding folder: " + dest_folder_loc_str)
time.sleep(3)
valid_command = 1
sys.exit(0)
else:
print ("Invalid command. Try again.")
Thursday, July 3, 2014
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)
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)
Subscribe to:
Posts (Atom)