开发者

Python - Create html page with hyperlinks from os.listdir

I have a script that creates a folder called "videos" on a USB dri开发者_StackOverflowve, 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()


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


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


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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜