tags:

views:

145

answers:

3

I have a script that creates a folder called "videos" on a USB drive, moves 6,500 WMV files over to the "videos" folder. Then it's suppose to create an HTML page with hyperlinks to each file. Here is my current example that's broken. I'm trying to have it crawl the videos directory and create an HTML page with hyperlinks only to the local files on the USB drive.

#!/usr/bin/python
import os.path
import os
import shutil
import re

# Create the videos directory in the current location
# If the directory exists ignore it
def createDirectory():
    directory = "videos"
    if not os.path.isdir("./" + directory + "/"):
        os.mkdir("./" + directory + "/")
        print "Videos Folder Created."
    else:
        print "Video Folder Exists."
        print "---------------------"

# Move all the files in the root directory with the .wmv extension
# to the videos folder
def moveVideos():
    for file in os.listdir("."):
        if os.path.splitext(file)[1] == ".wmv":
            print "Moving:", file
            shutil.move(file, os.path.join("videos", file))

def createHTML():
    videoDirectory = os.listdir("videos")
    f = open("videos.html", "w")
    f.writelines(videoDirectory)
    r = re.compile(r"(\\[^ ]+)")
    print r.sub(r'<a href="\1">\1</a>', videoDirectory)

createDirectory()
moveVideos()
createHTML()
A: 

Don't do f.writelines(videoDirectory) and then regex. Besides you're only printing to the console with that regex subsitution.

Do

videoDirectory = os.listdir("videos")
f = open("videos.html", "w")
f.write('<html><head></head><body><ul>'    
f.writelines(['<li><a href="videos/%s">%s</a></li>' % (f, f) for f in videoDirectory])
f.write('</ul></body></html>')
ntownsend
This one worked for me, thanks to everything for giving me the right direction.
Dunwitch
+6  A: 
import cgi

def is_video_file(filename):
  return filename.endswith(".wmv") # customize however you like

def createHTML():
  videoDirectory = os.listdir("videos")
  with open("videos.html", "w") as f:
    f.write("<html><body><ul>\n")
    for filename in videoDirectory:
      if is_video_file(filename):
        f.write('<li><a href="%s">%s</a></li>\n' %
                (cgi.escape(filename, True), cgi.escape(filename)))
    f.write("</ul></body></html>\n")
Roger Pate
+1: This is so much simpler than throwing a regexp around.
kigurai
+1 for proper escaping
digitalarbeiter
A: 
def createHTML():
    h = open("videos.html", 'w')
    for vid in os.listdir:
        path = "./videos" + vid
        f = open(path, r)
        h.write("<a href='"+f.name+"'>"+f.name[f.name.rfind('\\') +1 :]+"</a>")
        f.close()
    h.close()
    print "done writing HTML file"
inspectorG4dget